android: hide progressdialog whe the app regain control - android

I've an app that opens the facebook app when you click on a button, it works fine but on slow devices (like mine) facebook takes some seconds to show up, so i want to add a simple progressdialog that says "please wait"
i can show the progress dialog and open facebook with this code:
final ProgressDialog pd = ProgressDialog.show(contatti.this, "", "Attendere...", true);
Intent facebookIntent = getOpenFacebookIntent(getApplicationContext());
startActivity(facebookIntent);
//pd.dismiss();
the first time i tried, it worked fine but when i went back from facebook to my app the dialog was still showing, and i had no way to close it.
added dismiss() to try hide it, but it was a stupid idea >.<
how can i dismiss the dialog when the app regain control?

For this situation you have to check whether the application is sent background or not in on pause if it sent to background then close the dialog.
for checking the application is in bacground or not just have a look
android:how to check if application is running in background

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.gvsu.cis.toptracks.R;
import edu.gvsu.cis.toptracks.TopTrackListActivity;
import edu.gvsu.cis.toptracks.data.Customer;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class LastWebAPITask extends AsyncTask<String, Integer, String> {
private ProgressDialog progDialog;
private Context context;
private TopTrackListActivity activity;
private static final String debugTag = "LastWebAPITask";
public LastWebAPITask(TopTrackListActivity activity) {
super();
this.activity = activity;
this.context = this.activity.getApplicationContext();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(this.activity, "Search", this.context
.getResources().getString(R.string.looking_for_tracks), true,
false);
}
#Override
protected String doInBackground(String... params) {
try {
Log.d(debugTag, "Background:" + Thread.currentThread().getName());
String result = LastHelper.downloadFromServer(params);
return result;
} catch (Exception e) {
return new String();
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<Customer> trackdata = new ArrayList<Customer>();
progDialog.dismiss();
if (result.length() == 0) {
this.activity.alert("Unable to find track data. Try again later.");
return;
}
try {
JSONObject respObj = new JSONObject(result);
JSONArray tracks = respObj.getJSONArray("GetStockListResult");
for (int i = 0; i < tracks.length(); i++) {
JSONObject track = tracks.getJSONObject(i);
String Inventory_Status = track.getString("Inventory_Status");
String modify_Date = track.getString("modify_Date");
String msg = track.getString("msg");
String serial_nbr = track.getString("serial_nbr");
;
trackdata
.add(new Customer(Inventory_Status, modify_Date, msg, serial_nbr));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.activity.setTracks(trackdata);
}
}
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class LastHelper {
private static final String LastUrl = "http://etosxmldev.ctdi.com/ws/wcf/UNIVERSAL-DEMO/Service.svc/GetStockList?LocationId=300779360.svc/GetStockList/1111";
private static final int HTTP_STATUS_OK = 200;
private static byte[] buff = new byte[1024];
private static final String logTag = "LastHelper";
public static class ApiException extends Exception {
private static final long serialVersionUID = 1L;
public ApiException(String msg) {
super(msg);
}
public ApiException(String msg, Throwable thr) {
super(msg, thr);
}
}
protected static synchronized String downloadFromServer(String... params)
throws ApiException {
String retval = null;
String url = LastUrl;
Log.d(logTag, "Fetching " + url);
// create an http client and a request object.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
// execute the request
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
// handle error here
throw new ApiException("Invalid response from last.fm"
+ status.toString());
}
// process the content.
HttpEntity entity = response.getEntity();
InputStream ist = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();
int readCount = 0;
while ((readCount = ist.read(buff)) != -1) {
content.write(buff, 0, readCount);
}
retval = new String(content.toByteArray());
} catch (Exception e) {
throw new ApiException("Problem connecting to the server "
+ e.getMessage(), e);
}
return retval;
}
}
U have to use Asynctask class for doing this.Working Example for me.in your Activity class
LastWebAPITask lfmTask = new LastWebAPITask(
TopTrackListActivity.this);
lfmTask.execute(metroTxt);

thanks to another forum. looks like the fastest and simple way to do this is using onResume():
#Override
public void onResume(){
super.onResume();
if(waitdialog != null){ //check if we are resuming (not coming from another activity)
if (waitdialog.isShowing()) { //check if is showing
waitdialog.dismiss(); //dismiss
}
}
}

Related

Progress Dialog not displaying using Context in 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();
}
}
}
}

AsyncTask in Fragment not working and shows FATAL EXCEPTION: AsyncTask #1

The following code when run crashes my app. I am calling it in the MainActivity. When run it tells me:
FATAL EXCEPTION: AsyncTask #1 and directs me toward the ProgressDialog and Http Response Line
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import com.montel.senarivesselapp.model.ShowDataList;
import com.montel.senarivesselapp.model.Vessel;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class ShowallFragment extends Fragment {
//variables for JSON query
private static final String name ="vessel_name";
private static final String etad="eta_date";
private static final String etat="eta_time";
private static final String etbd="etb_date";
private static final String etbt="etb_time";
private static final String shippingName="shipping_agent_name";
private static final String v1 = "vessels";
private static final String v2 = "Vessel";
private ArrayList<Vessel> vList = new ArrayList<>();
private ArrayAdapter arrayAdapter = null;
private ListView listView = null;
private EditText et = null;
private ShowDataList ssadapter = null;
private View rootView;
public ShowallFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_showall, container, false);
setContentView(R.layout.fragment_showall);
setRetainInstance(true);
return rootView;
}
private void setContentView(int fragment_showall) {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
//For getting the JSON schedule from server
class Schedule extends AsyncTask<String, String, String> {
ProgressDialog loadDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Show the loading dialog
loadDialog = new ProgressDialog(ShowallFragment.this);
loadDialog.setMessage("Please wait....");
loadDialog.setCancelable(false);
loadDialog.show();
}
#Override
protected String doInBackground(String... uri) {
BufferedReader input = null;
String data = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://"));
StatusLine stline = response.getStatusLine();
if (stline.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
data = out.toString();
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(stline.getReasonPhrase());
}
} catch (HttpResponseException he) {
he.printStackTrace();
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
return data;
} catch (Exception e) {
System.out.println(e);
}
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Fill the vList array
Log.d("POST EXECUTE", result.toString());
loadDialog.dismiss();
if (result != null) {
try {
JSONObject jo = new JSONObject(result);
JSONArray vessels = jo.getJSONArray(v1);
Log.d("VESSEL LOG", vessels.toString());
vList = new ArrayList();
for (int i = 0; i < vessels.length(); i++) {
JSONObject vv = vessels.getJSONObject(i);
Log.d("VESSEL NAME", vv.getJSONObject(v2).getString(name));
vList.add(new Vessel(vv.getJSONObject(v2).getString(name),
vv.getJSONObject(v2).getString(etad),
vv.getJSONObject(v2).getString(etat),
vv.getJSONObject(v2).getString(etbd),
vv.getJSONObject(v2).getString(etbt),
vv.getJSONObject(v2).getString(shippingName)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listView = (ListView) rootView.findViewById(R.id.dataShow);
listView.setAdapter(arrayAdapter);
ssadapter = new ShowDataList(ShowallFragment.this , vList);
listView.setAdapter(ssadapter);
}
}
}
SecurityException: Permission denied (missing INTERNET permission
So you should request INTERNET permission in your projects AndroidManifest.xml file. Add on the rigth place:
<uses-permission android:name="android.permission.INTERNET" />
in your onPostExecute() change the position of Log.d("POST EXECUTE", result.toString()); to be inside catch so your code will look like this:
catch (Exception ee) {
ee.printStackTrace();
}
catch (JSONException e) {
Log.d("POST EXECUTE", e.toString());
} // catch (JSONException e)

UnknownHostException WebDav JackRabbit

I'm trying to implement a WebDav client in Android. For this purpose, I'm using a version of JackRabbit modified for Android that I got here (version 2.2.6).
I want to connect to my account in box.com and upload a file. Sincerely, I don't mind box or any other, i just happened to use this one.
Well, continuing with box.com, according to (this link)[https://support.box.com/hc/en-us/articles/200519748-Does-Box-support-WebDAV-] I should used "https://dav.box.com/dav" as server.
I have followed these links to build my code:
http://jackrabbit.apache.org/api/2.1/org/apache/jackrabbit/webdav/client/methods/package-summary.html
http://wiki.apache.org/jackrabbit/WebDAV
I'm getting an UnknownHostException sayingo my the URL I'm using for the server ("https://dav.box.com/dav") couldn't be found.
Any idea why does it not work? Otherwise, have you tried with other server and succeeded?
My code is here:
Thread t = new Thread() {
public void run(){
try {
String uri = "https://app.box.com/files";
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost(uri);
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
client.setHostConfiguration(hostConfig);
Credentials creds = new UsernamePasswordCredentials("USER", "PASSWORD");
client.getState().setCredentials(AuthScope.ANY, creds);
String baseUrl = "/";
File f = new File(Environment.getExternalStorageDirectory() + "/working-draft.txt");
PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
RequestEntity requestEntity = new InputStreamRequestEntity(
new FileInputStream(f));
method.setRequestEntity(requestEntity);
client.executeMethod(method);
}
catch (FileNotFoundException fnfe){
Log.i("SERVICE", "FileNotFoundException");
}
catch (HttpException he){
Log.i("SERVICE", "HttpException");
}
catch (IOException ioe){
Log.i("SERVICE", "IOException");
}
catch (Exception e){
Log.i("SERVICE", "Other Exception");
}
}
};
t.start();
I tried for a long time with JackRabbit and another webDav library but could not get it to work. This is how I eventually managed to send images to a WebDav hosted in IIS7 on a windows server. Hope this helps somebody.
SendImage.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import ntlm.NTLMSchemeFactory;
//import org.apache.http.client.HttpClient;
public class SendImage extends AsyncTask<String, Context, String> {
Context cxt;
public SendImage(Context cxtIn){
cxt = cxtIn;
}
#Override
protected String doInBackground(String... params) {
if (!Globals.sendImagesBeingPerformed) {
Globals.sendImagesBeingPerformed = true;
String filepath = cxt.getExternalFilesDir("/MyFileStorage/qrscans/").getAbsolutePath();
File myExternalFile = new File(filepath.toString());
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null && sdDirList.length>0){
for(int x=0;x<sdDirList.length;x++){
if(sdDirList[x].toString().endsWith(".jpg")){
File myExternalFile2 = new File(cxt.getExternalFilesDir("/MyFileStorage/qrscans/"), sdDirList[x].getName());
//String URL="";
System.out.println("SENDING QR4");
if(myExternalFile2.exists()) {
System.out.println("ScannedExists");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
String url = Globals.getWebDavUrl().trim();
String u = Globals.getWebDavUser().trim();
String p = Globals.getWebDavPass().trim();
String d = Globals.getWebDavDomain().trim();
if(d!=null && !d.isEmpty() && (d.length()>0)){
//use value of d as domain
}else{
//use a space as domain
d = " ";
}
String device = Globals.deviceId;
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new NTCredentials(u, p, device, d));
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),5000);
if(url.endsWith("/") || url.endsWith("\\")){
url = url.substring(0, url.length()-1);
}
HttpPut put = new HttpPut(url.trim()+"/"+sdDirList[x].getName());
put.setEntity(new FileEntity(sdDirList[x],"application/octet-stream"));
HttpResponse response = null;
try {
response = httpclient.execute(put);
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
System.out.println("execute done");
BufferedReader in = null;
String webResponse="";
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String stringLine="";
StringBuilder stringBuilder = new StringBuilder();
while ((stringLine = in.readLine()) != null) {
//stringBuilder.append("\n");
stringBuilder.append(stringLine);
}
webResponse=stringBuilder.toString()+"s";
if(webResponse.toString().trim().equalsIgnoreCase("s")){
myExternalFile2.delete();
}
System.out.println("webResponse:" + webResponse);
return null; //webResponse;
}catch(Exception e){
return "Error Sending Image:\n"+e.getMessage()+" " + e.getCause();
}
}
}
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(result!=null){
Toast.makeText(cxt, result, Toast.LENGTH_LONG).show();
}
Globals.sendImagesBeingPerformed = false;
super.onPostExecute(result);
}
}
NTLMSchemeFactory.java
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.impl.auth.NTLMScheme;
import org.apache.http.params.HttpParams;
public class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new JCIFSEngine());
}
}
JCIFSEngine.java
package ntlm;
import java.io.IOException;
import jcifs.ntlmssp.Type1Message;
import jcifs.ntlmssp.Type2Message;
import jcifs.ntlmssp.Type3Message;
import jcifs.util.Base64;
import org.apache.http.impl.auth.NTLMEngine;
import org.apache.http.impl.auth.NTLMEngineException;
public class JCIFSEngine implements NTLMEngine {
public String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException {
Type1Message t1m = new Type1Message(
Type1Message.getDefaultFlags(),
domain,
workstation);
return Base64.encode(t1m.toByteArray());
}
public String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException {
Type2Message t2m;
try {
t2m = new Type2Message(Base64.decode(challenge));
} catch (IOException ex) {
throw new NTLMEngineException("Invalid Type2 message", ex);
}
Type3Message t3m = new Type3Message(
t2m,
password,
domain,
username,
workstation,0);
return Base64.encode(t3m.toByteArray());
}
}

HTTP POST + ANDROID not giving response

I am beginner for Android. I want to send the data to my PHP page. but here i m trying to toast that post values. but there is no response. Plz help me.
My Code is:
public class send_msgActivity extends Activity{
//static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_msg);
Button btn_ok = (Button) findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText1 = (EditText)findViewById(R.id.sender);
String S_name = editText1.getText().toString();
EditText editText2 = (EditText)findViewById(R.id.reciever);
String S_email = editText2.getText().toString();
postData(S_name,S_email);
}
});
};
public void postData(String name,String email) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.URL.com/yourpage.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Fname", name));
nameValuePairs.add(new BasicNameValuePair("Femail", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
//HttpResponse response = httpclient.execute(httppost, new BasicResponseHandler());
HttpResponse response = httpclient.execute(httppost);
String reverseString = response.toString();
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
Use this example how to code HTTPpost method
package com.example.login;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;a
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class pdf extends Activity
{
public boolean connect=false,logged=false;
public String db_select;
ListView l1;
String mPwd,UName1="Success",UName,ret;
public Iterator<String> itr;
private String SERVICE_URL = "http://61.12.7.197:8080/Agero/person/pdf";
private String SERVICE_URL1 = "http://61.12.7.197:8080/Agero/person/url";
//private final String SERVICE_URL = "http://10.1.1.138:8080/Agero/person/pdf";
//private final String SERVICE_URL1 = "http://10.1.1.138:8080/Agero/person/url";
private final String TAG = "Course";
ArrayList<String> todoItems;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayAdapter<String> aa;
public List<String> list1=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf);
l1 = (ListView)findViewById(R.id.list);
todoItems = new ArrayList<String>();
aa = new ArrayAdapter<String>(this,R.layout.list_row,R.id.title,todoItems);
l1.setAdapter(aa);
todoItems.clear();
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user();
//display("hi");
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String name=(String)parent.getItemAtPosition(position);
/*Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show();
Intent i = new Intent(getBaseContext(),Webview.class);
i.putExtra("USERNAME", name);
startActivity(i);*/
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user1(name);
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
}
});
}
public void display(String msg)
{
Toast.makeText(pdf.this, msg, Toast.LENGTH_LONG).show();
}
private void validat_user()
{
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");
// wst.addNameValuePair("State", stg1);
// wst.addNameValuePair("Emp_PWD", stg2);
// db_select=stg1;
//display("I am");
wst.execute(new String[] { SERVICE_URL });
//display(SERVICE_URL);
}
private void validat_user1(String stg1)
{
db_select=stg1;
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Loading...");
wst.addNameValuePair1("PDF_NAME", stg1);
wst.execute(new String[] { SERVICE_URL1 });
}
#SuppressWarnings("deprecation")
public void no_net()
{
display( "No Network Connection");
final AlertDialog alertDialog = new AlertDialog.Builder(pdf.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
//alertDialog.setIcon(R.drawable.error_info);
alertDialog.setCancelable(false);
alertDialog.setButton("Close", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.cancel();
pdf.this.finish();
System.exit(0);
}
});
alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
display( "Accessing local DataBase.....");
alertDialog.cancel();
}
});
alertDialog.show();
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair1(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
#SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
} catch (Exception e) {
display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{ //display("JSON responce is : "+response);
if(!response.equals(""))
{
try {
JSONObject jso = new JSONObject(response);
int UName = jso.getInt("status1");
if(UName==1)
{
String status = jso.getString("status");
ret=status.substring(13,status.length()-2);
todoItems.add(0, status);
aa.notifyDataSetChanged();
}
else if(UName==-1)
{
String status = jso.getString("status");
//display(status);
Intent intObj=new Intent(pdf.this,Webview.class);
intObj.putExtra("USERNAME", status);
startActivity(intObj);
}
else
{
// int count=Integer.parseInt(UName);
// display("Number of Projects have been handling in AFL right now: "+count);
list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("reps1");
for(int i=0;i<array.length();i++)
{
list1.add(array.getJSONObject(i).getString("pdfName"));
}
itr=list1.iterator();
while(itr.hasNext())
{
//str1=itr.next()+"\n";
todoItems.add(0, itr.next().toString());
aa.notifyDataSetChanged();
}
//tv1.setText(str1);
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return;
}
}
else
{
display("unable to reach the server");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent intObj=new Intent(pdf.this, MainActivity.class);
intObj.putExtra("finish", true); // if you are checking for this in your other Activities
intObj.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intObj);
//pdf.this.finish();
finish();
return (true);
}
return super.onOptionsItemSelected(item);
}
}

Android-Json parser not able to display data retrieved from back end

I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}

Categories

Resources