Progress Dialog not displaying using Context in Android - android

I have a dialog fragment Java class which showing a dialog box it works so fine but the only problem is that the progressDialog is not showing while waiting for the response, this is different from the dialog box, this progressDialog works in AsyncTask while getting the response from the http.
here is my code:
package com.example.kapoyei.hatidtubigan.helper;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.kapoyei.hatidtubigan.R;
import com.example.kapoyei.hatidtubigan.other.Http;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class AddStation extends AppCompatDialogFragment implements View.OnClickListener {
public static String jsonObject; // THIS WILL BE THE HANDLER OF JSON LATER
Button btnCreate; // GET THE BUTTON
EditText etStationName, etAddress, etContact; // GET THE INPUT TEXT
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// CREATE A DIALOG BOX
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// GET THE LAYOUT
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_addstation, null);
builder.setView(view);
builder.setCancelable(true);
// GET THE VALUES
etStationName = (EditText) view.findViewById(R.id.etStationName);
etAddress = (EditText) view.findViewById(R.id.etAddress);
etContact = (EditText) view.findViewById(R.id.etContact);
btnCreate = (Button) view.findViewById(R.id.btnCreate);
// SET CLICK LISTENER OF THE BUTTON
btnCreate.setOnClickListener(this);
return builder.create();
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
Thread stationThread = new Thread() {
#Override
public void run() {
Looper.prepare();
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
}
};
stationThread.start();
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}
public class StoreStation extends AsyncTask<String, Void, String> {
ProgressDialog pd;
private Context mContext;
public StoreStation(Context c) {
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(mContext);
pd.setMessage("Adding station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
getResponse(result);
}
#Override
protected String doInBackground(String... url) {
String data = "";
jsonObject = "";
try {
String link = (String) url[0];
URL getURL = new URL(link);
HttpURLConnection huc = (HttpURLConnection) getURL.openConnection();
huc.setReadTimeout(10000);
huc.setConnectTimeout(15000);
huc.setRequestMethod("GET");
huc.setDoInput(true);
huc.connect();
InputStream is = huc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private void getResponse(String json) {
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("station");
String result = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
result = obj.getString("result");
}
if(result.equalsIgnoreCase("done")) {
Toast.makeText(mContext, "Successfully save!", Toast.LENGTH_LONG).show();
}
if(result.equalsIgnoreCase("exists")) {
Toast.makeText(mContext, "Station is already exists!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(mContext, "Connection problem", Toast.LENGTH_LONG).show();
}
}
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
}

In Android, only Main thread /UI thread can update UI
Other thread cannot update UI but your code is trying to run asynch task(which is a thread which run off/on UI accordingly, awesome!) in a worker thread which is causing the issues.
Solution: Execute Asynch task on UI thread
public void onClick(View view) {
if(view.getId() == R.id.btnCreate) {
if(etStationName.getText().toString().isEmpty() || etAddress.getText().toString().isEmpty() || etContact.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "All inputs are required!", Toast.LENGTH_LONG).show();
} else {
if(isNetworkAvailable()) {
String param = "n=" + etStationName.getText().toString() + "&a=" + etAddress.getText().toString() + "&c=" + etContact.getText().toString();
String endpoint = Http.url + "?type=addstation&" + param;
endpoint = endpoint.replace(" ", "%20");
new AddStation.StoreStation(getActivity()).execute(endpoint);
} else {
Toast.makeText(getActivity(), "Network unavailable", Toast.LENGTH_LONG).show();
}
}
}
}

Related

I would like to insert data to phpmyadmin from my android device

At the moment I can add users into the database through postman or emulator but I need to be able insert the data from actual android device .What adjustments do I have to take ? Please have a look at the code below
This is my main activity that I using in my app :
package ie.example.artur.adminapp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.HashMap;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
EditText editTextName,editTextEmail,editTextPassword;
TextView textView;
private static final String DB_URL = "jdbc:mysql://10.3.2.51/socialmedia_website";
private static final String USER = "zzz";
private static final String PASS = "zzz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
textView = (TextView) findViewById(R.id.textView);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void btnConn(View view) {
findViewById(R.id.layoutProgress).setVisibility(View.VISIBLE);
final ApiClient apiClient = new ApiClient();
String email = editTextEmail.getText().toString();
String name = editTextName.getText().toString();
String password = editTextPassword.getText().toString();
HashMap<String,String> parameters = new HashMap<>();
parameters.put("email",email);
parameters.put("name",name);
parameters.put("password",password);
Call<ApiResponse> call = apiClient.loginUser(parameters);
call.enqueue(new Callback<ApiResponse>() {
#Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if(response.isSuccessful())
{
ApiResponse apiResponse = response.body();
if(apiResponse.getStatus() == 200 || apiResponse.getStatus() == 201)
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
Send objSend = new Send();
objSend.execute("");
//Toast.makeText(MainActivity.this,"Success", Toast.LENGTH_SHORT);
textView.setText("Success.");
}
else
{
//Toast.makeText(MainActivity.this,apiResponse.getErrors(), Toast.LENGTH_SHORT);
textView.setText(apiResponse.getErrors());
}
}
else
{
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"Invalid api response.", Toast.LENGTH_SHORT);
textView.setText("Invalid api response.");
}
}
#Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
findViewById(R.id.layoutProgress).setVisibility(View.GONE);
//Toast.makeText(MainActivity.this,"No host available or please check network connectivity.", Toast.LENGTH_SHORT);
textView.setText("No host available or please check network connectivity.");
}
});
}
private class Send extends AsyncTask<String, String, String>
{
String msg = "";
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
#Override
protected void onPreExecute() {
textView.setText("Please Wait Inserting Data");
}
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
if (conn == null) {
msg = "Connection goes wrong";
} else {
String query = "Insert INTO users (name,email,password) VALUES('" + name+"','"+email+"','"+password+"')";
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
msg = "Inserting Successful!!";
}
conn.close();
}
catch(
Exception e
)
{
msg = "Connection goes Wrong";
e.printStackTrace();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {textView.setText(msg);}
}
}
Api client class
package ie.example.artur.adminapp;
import java.util.HashMap;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by asifj on 7/25/2017.
*/
public class ApiClient
{
private String BASE_URL = BuildConfig.BASE_URL;
ApiEndPoints apiService;
public ApiClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
apiService = retrofit.create(ApiEndPoints.class);
}
public Call<ApiResponse> loginUser(HashMap<String, String> parameters)
{
return apiService.usercreate(parameters);
}
}
If you need me to share any more class please let me know in the comments
//this is a class you'll call in you main activity
public class PostRequest extends AsyncTask<Void, Void, String> {
private String parameters;
private Context context;
public PostRequest(Context context) {
this.context = context;
Log.d("PostRequest", "Context set : " + context);
}
public void setParameters(String parameters) {
this.parameters = parameters;
Log.d("PostRequest", "Parameters set : " + parameters);
}
#Override
protected String doInBackground(Void... params) {
String response = null;
try {
URL url = new URL("url of your php script");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (IOException e) {
// Error
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//in your main activity you'll call it like so
PostRequest postRequest = new PostRequest(getContext());
postRequest.setParameters("param1=" + "param1value" + "&param2=" + "param2value");
postRequest.execute();

Data is not inserting into database of webhost from android

My data is not inserting to database of webhost.
Here is my ActionActivity.java from where I will send data to the database.
import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
public class ActionActivity extends Activity {
private String t;
TextView timer;
EditText e1,e2;
Button save;
static InputStream is = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action);
Bundle time = getIntent().getExtras();
t = (String) time.get("com.example.masba.timemanagement.MESSAGE");
e1 = (EditText) findViewById(R.id.editText);
e1.setText(t, TextView.BufferType.EDITABLE);
e2 = (EditText) findViewById(R.id.editText2);
save = (Button) findViewById(R.id.save);
}
public void insert(View view){
String actionName = e1.getText().toString();
String time = e2.getText().toString();
Toast.makeText(this, "Data Inserting...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(actionName, time);
e1.setText("");
e2.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Now my SignupActivity.java Which extends Asynctask.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String actionName = arg0[0];
String time = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?actioname=" + URLEncoder.encode(actionName, "UTF-8");
data += "&time=" + URLEncoder.encode(time, "UTF-8");
link = "http://masumalmasba.comli.com/insertdata.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Now my insertdata.php code is:
<?php
$servername="mysql6.000webhost.com";
$username = "a1871724_masum";
$password = "almasba012";
$dbname = "a1871724_actiont";
$conn = new mysqli($servername , $username , $password , $dbname);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$action = $_GET['actionname'];
$time = $_GET['time'];
$sql = "INSERT INTO actiontime (name,time) VALUES ('($action)','($time)')";
if($conn->query($sql)===TRUE){
echo "New record created succesfully";
}
else{
echo "Error";
mysql_close($conn);
}
?>

How do i connect mysql database and insert data into it using android code

I have mysql database on my hosting server
On simple android application I have feedback form and on submit I want to insert data into mysql database which is on server .
I tried google and found this following solution for local machine
how do I connect to my hosting server and mysql database without any php code?
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
Here
HttpPost httppost = new HttpPost("http://10.0.2.2/insert.php");
insert.php is mentioned means you have to put this file on server
just change the http://10.0.2.2/insert.php to the path of your server file path where the file is stored
Code for insert.php
// this variables is used for connecting to database and server
$host="yourhost";
$uname="username";
$pwd='pass';
$db="dbname";
// this is for connecting
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
// getting id and name from the client
if(isset($_REQUEST)){
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];}
// variable used to tell the client whether data is stored in database or not
$flag['code']=0;
// for insertion
if($r=mysql_query("insert into emp_info values('$name','$id') ",$con))
{
//if insertion succeed set code to 1
$flag['code']=1;
echo"hi";
}
// send result to client that will be 1 or 0
print(json_encode($flag));
//close
mysql_close($con);
?>
as mentioned in your code , this will get the value from server whether the data is stored or not by code=1 for stored and code = 0 for not stored
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
package fluent.techno.shreedurgajyotish;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import fluentindia.database.mysql.JsonHelper;
import fluentindia.tech.MenuAdapter.ProductAdapter;
import fluentindia.tech.MenuModel.ProductModel;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class Feedback extends Fragment
{
Button close,home,btnback,btnsend;
EditText edname,edcompany,edemail,edcontact,edwebsite,edaddress,edcomment;
String na,con,email,comm,advname,advem,advcontact,nacompany,web,add;
Spinner product;
JsonHelper Jobj;
String WebUrl, UrlImg;
JSONObject obj = null;
String Id,name,em,contact,AdvocateId,city;
ProductAdapter madappppppppppp;
ArrayList<ProductModel> llistttt;
int proid=0;
TextView textViewt2,t1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.feedback, null);
edname = (EditText)v.findViewById(R.id.editname);
edemail = (EditText)v.findViewById(R.id.editemail);
edcontact = (EditText)v.findViewById(R.id.editcontact);
edcomment = (EditText)v.findViewById(R.id.editcomment);
btnsend = (Button)v.findViewById(R.id.btnsend);
product = (Spinner)v.findViewById(R.id.editproduct);
textViewt2 = (TextView)v.findViewById(R.id.textViewt2);
t1 = (TextView)v.findViewById(R.id.textView1);
Bundle bung = this.getArguments();
if(bung!=null)
{
proid = bung.getInt("proid");
}
if(proid == 0)
{
Processtaluka pro = new Processtaluka();
pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectdistict.php"});
}
else
{
Processtaluka pro = new Processtaluka();
pro.executeOnExecutor(pro.THREAD_POOL_EXECUTOR, new String[]{"selectsingledistict.php?proid="+proid});
}
t1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent callweb = new Intent(Intent.ACTION_VIEW);
callweb.setData(Uri.parse("http://pulleycoupling.com/"));
startActivity(callweb);
}
});
textViewt2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9824155380"));
startActivity(callIntent);
}
});
btnsend.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
na=edname.getText().toString();
con=edcontact.getText().toString();
email=edemail.getText().toString();
comm = edcomment.getText().toString();
if(na==null||na==""||na.length()<2)
{
edname.setError("Please Enter Name");
}
else if(con == null || con == "" || con.length()<10)
{
edcontact.setError("Please Enter Contact");
}
else if(email == null || email == "" || email.length()<4)
{
edemail.setError("Please Enter Email");
}
else if(comm == null || comm== "" || comm.length()<2)
{
edcomment.setError("Please Enter Comment");
}
else
{
ProcessInquiry pro = new ProcessInquiry();
pro.execute(new String[]{"insertfeedback.php"});
}
}
});
return v;
}
private class ProcessInquiry extends AsyncTask<String, Void, Boolean>
{
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute()
{
dialog.setMessage("Please Wait Feedback send..");
dialog.show();
}
#Override
protected Boolean doInBackground(String... Url)
{
for(String Url1 : Url)
{
try
{
Jobj = new JsonHelper();
ArrayList<NameValuePair> pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("name", na));
pair.add(new BasicNameValuePair("contact", con));
pair.add(new BasicNameValuePair("email", email));
pair.add(new BasicNameValuePair("comment", comm));
pair.add(new BasicNameValuePair("product", city));
Jobj.MakeJsonCall(Url1, 2, pair);
Log.e("Url", Url1);
return true;
}
catch (Exception e)
{
return false;
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result==true)
{
Toast.makeText(getActivity(), "Feedback Send Sucessfully", 1000).show();
Intent i=new Intent(getActivity(),FragmentMaster.class);
i.putExtra("frgNo", "0");
startActivity(i);
edname.setText("");
edcomment.setText("");
edcontact.setText("");
edemail.setText("");
}
dialog.dismiss();
}
}
private class Processtaluka extends AsyncTask<String, Void, Boolean>
{
#Override
protected void onPreExecute()
{
}
#Override
protected Boolean doInBackground(String... Url)
{
for(String Url1 : Url)
{
Jobj = new JsonHelper();
obj = Jobj.MakeJsonCall(Url1, 2);
try
{
llistttt = new ArrayList<ProductModel>();
JSONArray JArr = obj.getJSONArray("record");
if(proid == 0)
{
}
else
{
}
for(int i=0;i<JArr.length();i++)
{
JSONObject dObj = JArr.getJSONObject(i);
llistttt.add(new ProductModel( dObj.getString("sub_id"), dObj.getString("sub_name")));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return true;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
madappppppppppp = new ProductAdapter(getActivity(),llistttt);
product.setAdapter(madappppppppppp);
product.setPrompt("Select The Service You Want");
product.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
city= llistttt.get(arg2).getSubname();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
}

Cannot display toast in a catch

package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.

CancellationException while using AsyncTask in Android?

I am using AsyncTask in my application and sometimes when I run the application I get the error as java.util.cancellationexception.
Can someone let me know the reason of this error or the way this can be removed?
import java.util.concurrent.ExecutionException;
import com.babbleville.io.BabbleVilleSyncTask;
import com.babbleville.io.GetCurrentLocation;
import com.babbleville.utils.BabbleVilleWebServiceUrl;
import com.babbleville.utils.ConstantCodes;
import com.babbleville.utils.LoadContent;
import com.babbleville.io.LoginParse;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BabbleVilleMainActivity extends Activity implements OnClickListener
{
private Button btnLogin = null;
private Button btnNewUserSignUp = null;
private Button btnForgotPwd = null;
//private boolean loginFlag = false;
private EditText emailId = null;
private EditText password = null;
private String userName = null;
private String pwd = null;
String url = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
btnLogin = (Button) findViewById (R.id.btnLogin);
btnNewUserSignUp = (Button) findViewById(R.id.btnNewUser);
btnForgotPwd = (Button) findViewById(R.id.btnForgotPwd);
emailId = (EditText) findViewById(R.id.emailId);
password = (EditText) findViewById(R.id.password);
//Temporary. Should be removed later on.
emailId.setText("sunil#softwebsolutions.com");
password.setText("sunil123");
btnLogin.setOnClickListener(this);
btnNewUserSignUp.setOnClickListener(this);
btnForgotPwd.setOnClickListener(this);
}
/**
* This is the overriden method for getting the click events.
* #param View v = is the view on which click event this method is called.
* For eg, on Login click button v will btnLogin.
*/
public void onClick(View v)
{
if(v == btnLogin)
{
userName = emailId.getText().toString().trim();
pwd = password.getText().toString().trim();
System.out.println("User name ==> " + userName);
System.out.println("Password ==> " + pwd);
if(userName == null || pwd == null || userName.equals("") || pwd.equals(""))
{
Toast toast = Toast.makeText(BabbleVilleMainActivity.this, "Please enter your Username and Password!", 50);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else
{
url = null;
/*url = ConstantCodes.LOGIN_URL + ConstantCodes.ACTION + "=" + ConstantCodes.LOGIN_ACTION + "&" +
ConstantCodes.EMAILID + "=" + this.userName + "&" + ConstantCodes.PWD + "=" + this.pwd ;*/
url = BabbleVilleWebServiceUrl.getLoginURL() + ConstantCodes.EMAILID + "=" + this.userName + "&" + ConstantCodes.PWD + "=" + this.pwd ;
System.out.println("Login URL ==> " + url);
BabbleVilleSyncTask loginTask = new BabbleVilleSyncTask(v.getContext());
loginTask.execute(url);
//System.out.println("status===>"+loginTask.getStatus());
try
{
String result = loginTask.get().trim();
System.out.println("Result returned from Login Task ==> " + result);
LoginParse.loginParser(result);
if(LoginParse.getLoginAck())
{
/*ConstantCodes.BABBLE_START_NUM = 0;
ConstantCodes.BABBLE_END_NUM = 5;*/
// loadBabbles();
GetCurrentLocation location = new GetCurrentLocation(v.getContext());
String lat = location.getCurrentLatitude();
String lon = location.getCurrentLongitude();
System.out.println("Latitude ==> " + lat + " Longitude ==> " + lon);
//Babble babble_add_data = new Babble(BabbleVilleMainActivity.this,"babble");
LoadContent loadContent = new LoadContent(BabbleVilleMainActivity.this);
loadContent.loadBabbles(lat, lon);
loadContent.loadVilles();
//loadContent.loadUserDetails();
//mContext = v.getContext();
Intent homeScreenIntent = new Intent(BabbleVilleMainActivity.this, HomeScreenActivity.class);
BabbleVilleMainActivity.this.startActivity(homeScreenIntent);
}
else
{
Toast toast = Toast.makeText(BabbleVilleMainActivity.this, "Username or Password is incorrect", 50);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
}
}
else if(v == btnForgotPwd)
{
Intent forgetPwdIntent = new Intent(BabbleVilleMainActivity.this, ForgotPasswordActivity.class);
BabbleVilleMainActivity.this.startActivity(forgetPwdIntent);
}
else if(v == btnNewUserSignUp)
{
Intent newUserIntent = new Intent(BabbleVilleMainActivity.this, NewUserSignUpActivity.class);
BabbleVilleMainActivity.this.startActivity(newUserIntent);
}
}
}
The exception occurs at String result = loginTask.get().trim().
Can you let me know now what is the problem?
package com.babbleville.io;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class BabbleVilleSyncTask extends AsyncTask<String, Void, String>
{
private Context context = null;
private final HttpClient httpClient = new DefaultHttpClient();
private String content = null;
private String error = null;
private ProgressDialog progressDialog = null;
private String finalResult = null;
public BabbleVilleSyncTask(Context context)
{
this.context = context;
progressDialog = new ProgressDialog(this.context);
}
protected void onPreExecute()
{
progressDialog.setMessage("Please Wait....");
progressDialog.show();
}
protected String doInBackground(String... urls)
{
try
{
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = httpClient.execute(httpget, responseHandler);
}
catch (ClientProtocolException e)
{
error = e.getMessage();
Log.e("ClientProtocolException", error);
cancel(true);
}
catch (IOException e)
{
error = e.getMessage();
Log.e("IOException", error);
cancel(true);
}
httpClient.getConnectionManager().shutdown();
return content;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
}
Please let me know how can I use the result returned in onPostExecute.

Categories

Resources