Here is my java code for loading a title, description, date and an image from Mysql through Php in a loop. Everything loading perfectly except image. When I load image the loading dialog box displaying and I can see only one image in the background but the loading dialogue box is still appearing. I'm new in android so I need experts help like you.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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 (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog = new ProgressDialog(getActivity());
pDialog.dismiss();
}
pDialog.dismiss();
}
}
your code seems to be ok.
also check some option like volley
Try something like following
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
To call this
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
To dismiss dialog show the dialog only once before for loop and dismiss it after for loop
Hope it will help :)
Related
i want to display an employee last clock-in from a web server. The problem is i'm not really sure how to retrieve a single last clock-in and display it to a textview. Here is my code, JSONParser.java:
package com.example.win7.simpleloginapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
int timeout=10000; //in milisecond = 10 detik
// constructor
public JSONParser() {
//timeout = new Values().gettimeout();
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException ste)
{
Log.e("Timeout Exception: ", ste.toString());
}
catch (ConnectTimeoutException e)
{
Log.e("Timeout Exception: ", e.toString());
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
ServerRequest.java:
package com.example.win7.simpleloginapp;
import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.impl.io.HttpRequestParser;
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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class ServerRequest {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = ".................net";
final static String TAG_USER = "user";
private Context mContext;
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String NameStr = "Name";
JSONArray user;
JSONParser jsonParser = new JSONParser();
public ServerRequest(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing..");
progressDialog.setMessage("Please Wait....");
mContext = context;
}
public void storeUserDataInBackground(user user, GetUserCallback userCallback) {
progressDialog.show();
new StoreUserDataAsyncTask(user, userCallback).execute();
}
public void fetchUserDataInBackground(user user, GetUserCallback callBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user, callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
user user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("http://.........................../register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public class fetchUserDataAsyncTask extends AsyncTask< Void, Void, user> {
user user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected user doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("................................../fetchUserData.php");
user returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length()==0)
{
returnedUser = null;
}
else
{
String Name1 = jObject.getString("Name");
//String Name1 = "ekin";
storeData(Name1);
//Name1 = "hello";
returnedUser = new user(user.username, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(user returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
public SharedPreferences getSharedPref(){
return mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
}
public void storeData(String Name1) {
getSharedPref().edit().putString("data", Name1).apply();
}
public String getData(){
return getSharedPref().getString("data", "");
}
}
And here is the MainActivity.java:
package com.example.win7.simpleloginapp;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import android.app.AlertDialog;
import android.location.LocationListener;
import com.example.win7.simpleloginapp.model.JSONParser2;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button button_logout;
TextView etUsername , etName, lastTimeDisp, lastDateDisp; //baru
UserLocalStore userLocalStore;
Button clockIN1, clockOUT1;
Date date = new Date();
String AndroidId;
String username;
double longitude;
double latitude;
private TextView locationText;
private TextView addressText;
private GoogleMap map;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
JSONArray user = null;
JSONParser jsonParser = new JSONParser();
public static final String TAG_SUCCESS = "success";
public static final String TAG_USER = "user";
public static final String TAG_STAFF_ID = "staffID";
public static final String TAG_DATE = "date";
public static final String TAG_TIME = "time";
public static final String TAG_LONG = "longitude";
public static final String TAG_LAT = "latitude";
private Button scannerButton;
private Button camButton;
String staffIDStr, dateStr, timeStr, latitudeStr, longitudeStr;
String user_name;
SharedPreferences sharedPreferences;
public static final String mypreference = "MyPrefs" ;
public static final String NameStr = "Name";
ActionBar actionbar;
TextView textview;
LayoutParams layoutparams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBarTitleGravity();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3B5999")));
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
setContentView(R.layout.activity_main);
etUsername = (TextView) findViewById(R.id.etUsername);
etName = (TextView) findViewById(R.id.etName);
lastTimeDisp = (TextView) findViewById(R.id.lastTimeDisp); //baru
lastDateDisp = (TextView) findViewById(R.id.lastDateDisp); //baru
button_logout = (Button) findViewById(R.id.bLogout);
AnalogClock ac = (AnalogClock) findViewById(R.id.analogClock1);
DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
clockIN1 = (Button) findViewById(R.id.clockIN);
clockOUT1 = (Button) findViewById(R.id.clockOUT);
etUsername.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
etName.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.apply(); //baru - tukar commit() ke apply()
ServerRequest serverRequest = new ServerRequest(getApplicationContext());
ServerRequest2 serverRequest2 = new ServerRequest2(getApplicationContext());
Log.d("", "The value is : " + serverRequest.getData());
String username1 = serverRequest.getData();
String timeL = serverRequest2.getData();
String dateL = serverRequest2.getData();
etName.setText(username1);
lastTimeDisp.setText(timeL); //baru
lastDateDisp.setText(dateL); //baru
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
replaceMapFragment();
clockIN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//date.setTime(System.currentTimeMillis()); //set to current time
clockIN1.setClickable(false);
Calendar c = Calendar.getInstance();
dateStr = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
timeStr = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE);
staffIDStr = etUsername.getText().toString();
new createClockIn().execute();
clockIN1.setEnabled(false);
clockIN1.setClickable(false);
}
});
userLocalStore = new UserLocalStore(this);
}
private void ActionBarTitleGravity() {
actionbar = getSupportActionBar();
textview = new TextView(getApplicationContext());
layoutparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutparams);
textview.setText("MysysESS");
textview.setTextColor(Color.WHITE);
textview.setGravity(Gravity.CENTER);
textview.setTextSize(25);
textview.setTypeface(Typeface.DEFAULT_BOLD);
actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(textview);
}
class createClockIn extends AsyncTask<String, String, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("LOADING.");
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_STAFF_ID, staffIDStr));
params.add(new BasicNameValuePair(TAG_DATE, dateStr));
params.add(new BasicNameValuePair(TAG_TIME, timeStr));
params.add(new BasicNameValuePair(TAG_LONG, longitudeStr));
params.add(new BasicNameValuePair(TAG_LAT, latitudeStr));
JSONObject json = jsonParser.makeHttpRequest("http://.........................../createClockIN.php", "POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
finish();
} else {
return "gagal_database";
}
} catch (JSONException e)
{
e.printStackTrace();
return "gagal_koneksi_or_exception";
}
return "sukses";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equalsIgnoreCase("gagal_database")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "There is a problem , check your connection DB!", Toast.LENGTH_SHORT).show();
} else if (result.equalsIgnoreCase("gagal_koneksi_or_exception")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "There is a problem , check your connection!", Toast.LENGTH_SHORT).show();
} else if (result.equalsIgnoreCase("sukses")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "Lets work!", Toast.LENGTH_SHORT).show();
String staffID1 = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("username", staffID1);
startActivity(intent);
}
}
}
//on start function login function
#Override
protected void onStart() {
super.onStart();
if (authenticate() == true)
displayUserDetails();
else
startActivity(new Intent(MainActivity.this, login.class));
}
private boolean authenticate() {
return userLocalStore.getUserLoggedIn();
}
private void displayUserDetails() {
user user = userLocalStore.getLoggedInUser();
etUsername.setText(user.username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
LinearLayout main_view = (LinearLayout) findViewById(R.id.main_view);
switch (item.getItemId()) {
case R.id.logout:
userLocalStore.clearUserData();
startActivity(new Intent(this, login.class));
finish();
return true;
case R.id.history:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
String username1 = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), ListHistory.class);
intent.putExtra("username", username1);
startActivity(intent);
return true;
case R.id.location:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
String username2 = etUsername.getText().toString();
Intent intent2 = new Intent(getApplicationContext(), LocationActivity.class);
intent2.putExtra("username", username2);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// super.onBackPressed(); // Comment this super call to avoid calling finish()
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
View frag = findViewById(R.id.map);
frag.setVisibility(View.INVISIBLE);
map.getUiSettings().setZoomGesturesEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
longitudeStr = Double.toString(longitude);
latitudeStr = Double.toString(latitude);
if ((longitude > 101.650000 && longitude < 101.670000 && latitude > 2.925000 && latitude < 2.927000) ||
(longitude > 101.640000 && longitude < 101.660000 && latitude > 2.900000 && latitude < 2.920000) ||
(longitude > 101.680000 && longitude < 101.700000 && latitude > 3.140000 && latitude < 3.170000) ||
(longitude > 103.620000 && longitude < 103.640000 && latitude > 1.640000 && latitude < 1.660000))
{
clockIN1.setEnabled(true);
scannerButton.setEnabled(true);
camButton.setEnabled(true);
} else {
Toast.makeText(MainActivity.this, "YOU ARE NOT IN THE OFFICE!", Toast.LENGTH_SHORT).show();
clockIN1.setEnabled(false);
scannerButton.setEnabled(false);
camButton.setEnabled(false);
}
new GetAddressTask(MainActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
}
};
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Settings your GPS",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
For your information, I have to retrieve the data from another web server url(http://........................./lastClock.php) and the name of the entity from the table is dclkrec(represent date) and cclktime(represent time).
Any help from you guys would be very appreciated. Thank you in advanced.
You are doing a lot of wheel reinvention here. There are tools for networking and serialising/deserialising data.
For networking I can recommend Retrofit
Working with JSON objects Gson
Try these and your life will be much easier. Trust me. It is worth investing a little time.
I tried more and more and nothing is worked.Last i used sharedPreferences.but that not relevant to me...Please help me to replace the sharedPreferences..
my MainActivity is
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.CancellationSignal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView textView,textView2;
String[] name=new String[100];
String[] id=new String[100];
String[] names=null;
String[] idg=new String[100];
String[] ids=null;
int i;
int len;
ArrayList<NewsItem> listData;
int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Fetch().execute();
SharedPreferences sharedPreferences = getSharedPreferences("local", 0);
SharedPreferences.Editor editor=sharedPreferences.edit();
size = sharedPreferences.getInt("array_size", 0);
ids = new String[size];
names = new String[size];
for(i=0; i<size; i++){
ids[i]=sharedPreferences.getString("array1_" + i, null);
names[i]=sharedPreferences.getString("array2_" + i, null);
}
editor.clear();
editor.commit();
listData = getListData();
final ListView listView = (ListView) findViewById(R.id.custom_list);
listView.setAdapter(new CustomListAdapter(this, listData));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
NewsItem newsData = (NewsItem) listView.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
}
});
//textView=(TextView)findViewById(R.id.textView);
//textView2=(TextView)findViewById(R.id.textView2);
}
class Fetch extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
dialogInterface.cancel();
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://andrinfo.comli.com/rimgid.php";
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
len = Jarray.length();
for(i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
id[i] ="http://developer.andrinfo.comli.com/img/"+ Jasonobject.getInt("id")+".jpg";
name[i] = Jasonobject.getString("name");
SharedPreferences sharedPreferences=getSharedPreferences("local",0);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("array_size", len);
for(int i=0;i<len; i++) {
editor.putString("array1_" + i, id[i]);
editor.putString("array2_" + i, name[i]);
}
editor.apply();
drac d=new drac();
//d.exe(id,name,len);
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
private ArrayList<NewsItem> getListData() {
ArrayList<NewsItem> listMockData = new ArrayList<NewsItem>();
String[] images = getResources().getStringArray(R.array.images_array);
String[] headlines = getResources().getStringArray(R.array.headline_array);
for (i = 0; i < size; i++) {
NewsItem newsData = new NewsItem();
newsData.setUrl(ids[i]);
newsData.setHeadline(names[i]);
newsData.setReporterName("Price");
newsData.setDate("May 26, 2015, 1:35PM");
listMockData.add(newsData);
}
return listMockData;
}
class drac{
public void exe(String[] ids, String[] idg,int size)
{
for (i = 0; i < size; i++) {
Toast.makeText(getApplicationContext(), ""+ids[i], Toast.LENGTH_SHORT).show();
}}}
}
And the PROBLEM IS IN MainActivity.java
See http://developer.android.com/intl/es/reference/android/os/AsyncTask.html. Especially the part with the result.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
Finally I solved by using volley library thanks for the response.
I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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 com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
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.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I'm trying to make a POST request with Android, but I'm not succeeding. I think the problem is in how to set the parameters for resquisição and Header. Below is my method I do the request ...
public void testPostDate() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
Gson gson = new Gson();
CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo",
"descrição", 10.00, 30.00);
CrimePOST crimePost = new CrimePOST();
crimePost.setCrime(crime);
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs="));
String json = gson.toJson(crimePost);
String paramString = URLEncodedUtils.format(params, Utils.ENCODE);
try {
HttpPost post = new HttpPost(
"http://safe-sea-4024.herokuapp.com/crimes/mobilecreate"
+ "?" + paramString);
post.setHeader("Content-Type", "application/json");
StringEntity entitty = new StringEntity(json);
entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(entitty);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = toString(in);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This method is responsible for converting an inputStream to String
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
Really I am passing the Header correctly?
You have to do this in an AsyncTask
I wrote this tutorial while back. it does send json data via HTTP Post to a url. Check it out. Original post can be found here:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity implements LocationListener{
private TextView textView =null;
LocationManager locationManager=null;
Location location=null;
protected String url;
protected JSONObject jsonData=null;
private EditText urlText=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gpsEnabled!=true) {
Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
textView = (TextView)findViewById(R.id.textView);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
urlText = (EditText)findViewById(R.id.urlTextbox);
Button submitButton = (Button)findViewById(R.id.submitUrl);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (urlText.getText()!=null) {
url=urlText.getText().toString();
System.out.println(url);//for testing only, not required
Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString());//not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public class HttpPostHandler extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = null;
try {
dataEntity = new StringEntity(jsonData.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(dataEntity);
httpPost.setHeader("Content-Type", "application/json");
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class MainActivity extends Activity {
GridView gridView;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.grid_view);
adapter=new LazyAdapter(this, mStrings);
gridView.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
adapter.imageLoader.stopThread();
gridView.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
private String[] mStrings={
"http://www.globaltvbc.com/uploadedImages/Global_News/Content/Wallpaper.jpeg",
"http://cdn.windows7themes.net/themes/halo-3-hd-wallpaper.jpg",
};
}
The question is i want to display the item on the gridview and display the item in full screen.I want to include any code to display the gridview item in full screen to be in the same class as MainActivity.I dont want my code to be in a new class.
if you want to load the full screen on the same activity then you should use popup window for displaying the image.
or the best solution is implement onItemClickListener on your main activity and on click get the item by position and pass the image url to next activityfor loading it there.
I am giving you my code edit this according to your need
|main Activity
package com.mypack;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
public class GridViewActivity extends Activity implements OnItemClickListener {
List<RowItem4> rowItems;
private GridView gridView;
private Button galleryButton;
private Button shareButton;
private String[] mStringArray;
public static final Integer[] partyid = { 1, 2, 3, 4, 18, 19, 20 };
int i = 1;
private String xml;
String output = "";
/*private static final String NAMESPACE = "";
private static final String URL = "";
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "";*/
private int pos;
private ProgressDialog progressDialog;
private int galleryId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
Intent i = getIntent();
pos = i.getIntExtra("position", 0);
galleryId = i.getIntExtra("galleryId", 0);
progressDialog = ProgressDialog.show(GridViewActivity.this, "",
"Loading...");
Thread myThread = new Thread() {
private GridViewAdapter adapter;
public void run() {
getImages();
rowItems = new ArrayList<RowItem4>();
for (int i = 0; i < mStringArray.length; i++) {
RowItem4 item = new RowItem4(mStringArray[i]);
rowItems.add(item);
}
// LoadImageFromURL(""
// + output);
adapter = new GridViewAdapter(GridViewActivity.this, rowItems);
runOnUiThread(new Runnable() {
public void run() {
try {
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(GridViewActivity.this);
progressDialog.dismiss();
} catch (final Exception ex) {
Log.i("---", "Exception in thread");
}
}
});
}
};
myThread.start();
setUpView();
}
private void getImages() {
final String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:tns=\"urn:registerwsdl\">" + "<SOAP-ENV:Body>"
+ "<tns:register " + "xmlns:tns=\"urn:registerwsdl\">"
+ "<galleryid xsi:type=\"xsd:integer\">" + galleryId
+ "</galleryid>" + "<partyid xsi:type=\"xsd:integer\">"
+ partyid[pos] + "</partyid>" + "</tns:register>" +
// "</SOAP-ENV:Body></SOAP-ENV:Envelope>",Name,Email,Password,Status,Type,Date];
"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
System.out.println("------------" + envelope);
CallWebService(URL, SOAP_ACTION, envelope);
org.w3c.dom.Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
ArrayList<String> myList = new ArrayList<String>();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
NodeList nl1 = doc.getElementsByTagName("response");
for (int j = 0; j < nl1.getLength(); j++) {
NodeList nl = doc.getElementsByTagName("url");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
myList.add(node.getFirstChild().getNodeValue());
}
}
mStringArray = new String[myList.size()];
mStringArray = myList.toArray(mStringArray);
for (int i = 0; i < mStringArray.length; i++) {
Log.d("string is", (mStringArray[i]));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
String CallWebService(String url, String soapAction, String envelope) {
final DefaultHttpClient httpClient = new DefaultHttpClient();
// request parameters
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 25000);
// set parameter
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);
// POST the envelope
HttpPost httppost = new HttpPost(url);
// add headers
httppost.setHeader("soapaction", soapAction);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
String responseString = "";
try {
// the entity holds the request
HttpEntity entity = new StringEntity(envelope);
httppost.setEntity(entity);
// Response handler
ResponseHandler<String> rh = new ResponseHandler<String>() {
// invoked when client receives response
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// get response entity
HttpEntity entity = response.getEntity();
// read the response as byte array
StringBuffer out = new StringBuffer();
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
responseString = httpClient.execute(httppost, rh);
} catch (Exception e) {
Log.v("exception", e.toString());
}
xml = responseString.toString();
// close the connection
System.out.println("xml file ------" + xml);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (i == 2) {
if (galleryButton.getVisibility() == View.VISIBLE) {
galleryButton.setVisibility(View.INVISIBLE);
shareButton.setVisibility(View.INVISIBLE);
} else {
galleryButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
}
i = 0;
}
i++;
super.dispatchTouchEvent(ev);
return false;
}
/*
* public OnTouchListener touch = new View.OnTouchListener() {
*
* public boolean onTouch(View v, MotionEvent event) {
* //System.out.println("onTouch =============-----------"); if
* (galleryButton.getVisibility() == v.VISIBLE) {
* galleryButton.setVisibility(v.INVISIBLE);
*
* shareButton.setVisibility(v.INVISIBLE);
*
* } else { galleryButton.setVisibility(v.VISIBLE);
*
* shareButton.setVisibility(v.VISIBLE);
*
* } return false; } };
*/
private void setUpView() {
gridView = (GridView) findViewById(R.id.gridView1);
galleryButton = (Button) findViewById(R.id.gallery_button);
shareButton = (Button) findViewById(R.id.share_button);
// relativeLayout1.setOnTouchListener(touch);
}
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), ShowImageActivity.class);
i.putExtra("image", mStringArray[position]);
i.putExtra("galleryId", galleryId);
startActivity(i);
}
}
RowItem4 Object Class
package com.mypack;
public class RowItem4 {
private String imageId;
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public RowItem4(String mStringArray) {
this.imageId = mStringArray;
}
}
GridViewAdapter extending BaseAdapter
package com.mypack;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class GridViewAdapter extends BaseAdapter {
Context context;
List<RowItem4> rowItems;
private ViewHolder holder;
private Drawable d;
public GridViewAdapter(Context context, List<RowItem4> rowItems) {
super();
this.context = context;
this.rowItems = rowItems;
}
private class ViewHolder {
ImageView imageView;
public int position;
}
public int getCount() {
// TODO Auto-generated method stub
return rowItems.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return rowItems.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return rowItems.indexOf(getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_image_view, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem4 rowItem = (RowItem4) getItem(position);
holder.position = position;
GetXMLTask task = new GetXMLTask(position,holder);
task.execute(new String[] { ""+rowItem.getImageId() });
//holder.imageView.setImageDrawable(d);
return convertView;
}
/*private Drawable LoadImageFromURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
d = Drawable.createFromStream(is, "src");
return d;
}catch (Exception e) {
System.out.println(e);
return null;
}
}*/
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
private int mPosition;
private ViewHolder mHolder;
public GetXMLTask(int position, ViewHolder holder) {
mPosition = position;
mHolder = holder;
}
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
protected void onPostExecute(Bitmap result) {
if (mHolder.position == mPosition)
{
mHolder.imageView.setImageBitmap(result);
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
This code is if you want to load the image on second activity,and if you want to load image on the same activity just add the code for adding popup window in the main activity. I think now it is clear