I am using Asynctask to extract some data from the web and use it in further calculations. I have implemented a connectivity check as well, it returns false if there is no connection but It crashes if there is internet connection and "the server is down". I want to display a dialog to notify the user that their internet is experiencing problems. But I can't seem to get it right. Please help. Thanks in advance. :)
HttpClient client;
String URL, re, element;
JSONObject json, getjson;
int i, j, statusCode;
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
InputStream is;
BufferedReader reader;
StringBuilder sb, sb1;
SharedPreferences getinput, passjson;
ProgressDialog pd;
Context context = DataRetrieve.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dataretrieve);
// Bundle gotBasket = getIntent().getExtras();
// URL = gotBasket.getString("key");
getinput = getSharedPreferences("input", 0);
URL = getinput.getString("key", null);
if (!isNetworkReachable()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("No Network Connection");
builder.setMessage("The Network is unavailable. Please check your internet connection.");
builder.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent m = new Intent(
android.provider.Settings.ACTION_SETTINGS);
startActivity(m);
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Intent n = new Intent(DataRetrieve.this,
OpTilt.class);
startActivity(n);
}
});
builder.create().show();
} else {
Read r = new Read();
r.execute();
}
}
private boolean isNetworkReachable() {
// TODO Auto-generated method stub
ConnectivityManager mManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo current = mManager.getActiveNetworkInfo();
if (current != null && current.isConnectedOrConnecting()) {
return true;
}
return false;
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DataRetrieve.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
re = null;
is = null;
json = null;
try {
httpget = new HttpGet(URL);
client = new DefaultHttpClient();
response = client.execute(httpget);
entity = response.getEntity();
is = entity.getContent();
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
statusCode = -1;
Log.e("log_tag", "Erro http " + e.toString());
}
if (statusCode == 200) {
try {
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
re = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Erro conversão " + e.toString());
}
}
return re;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pd.dismiss();
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
SharedPreferences sendHm;
sendHm = getSharedPreferences("parsedata", 0);
SharedPreferences.Editor editor = sendHm.edit();
for (int k = 0; k < H.length; k++) {
editor.putString("Hm" + k, H[k]);
}
editor.commit();
Intent f = new Intent(DataRetrieve.this, Calculator.class);
startActivity(f);
/*
* Bundle bundle = new Bundle(); bundle.putStringArray("key1",
* H); Intent f = new Intent(DataRetrieve.this,
* Calculator.class); f.putExtras(bundle); startActivity(f);
*/
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
change your postExcute method code to below (you should check the result is not null or empty)
pd.dismiss();
if(!TextUtils.isEmpty(result))
{
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
SharedPreferences sendHm;
sendHm = getSharedPreferences("parsedata", 0);
SharedPreferences.Editor editor = sendHm.edit();
for (int k = 0; k < H.length; k++) {
editor.putString("Hm" + k, H[k]);
}
editor.commit();
Intent f = new Intent(DataRetrieve.this, Calculator.class);
startActivity(f);
/*
* Bundle bundle = new Bundle(); bundle.putStringArray("key1",
* H); Intent f = new Intent(DataRetrieve.this,
* Calculator.class); f.putExtras(bundle); startActivity(f);
*/
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
Related
I was creating android project in that i am using itemlist view and pagination . while clicking on that particular item i want to get that item id.but i am not getting the unique id.
When i use position then each and every page it is getting form 0-9.
i have the field 'audit_id'. i want to assign this values as item id and i want to get . whether it is possible?
My Code is :
private class AsyncLogin extends AsyncTask<String, String, StringBuilder> {
ProgressDialog pdLoading = new ProgressDialog(Tblview.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected StringBuilder doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.1.99/ashwad/ims/webservices/alldata.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "sdfa")
.appendQueryParameter("password", "asffs");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return null;
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
result = new StringBuilder();
String next1;
while ((next1 = bufferedReader.readLine()) != null) {
result.append(next1 + "\n");
}
Log.e("dfasf",result.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return result;
}
#Override
protected void onPostExecute(StringBuilder s) {
super.onPostExecute(s);
try {
JSONArray login;
JSONObject obj = new JSONObject(s.toString());
if(s.toString().contains("Result")) {
data = new ArrayList<String>();
login = obj.getJSONArray("Result");
for(int i=0;i<login.length();i++) {
JSONObject c = login.getJSONObject(i);
productsArray = c.getJSONArray(Latest_Products);
TOTAL_LIST_ITEMS=productsArray.length();
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
pageCount = (TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE)+val;
for (int j = 0; j < productsArray.length(); j++) {
JSONObject cc = productsArray.getJSONObject(j);
//------------------------------------------------------------------------
Log.e("audit",cc.getString("phone_name"));
String audit_id_str = cc.getString("audit_id");
int audit_id =Integer.parseInt(audit_id_str);
listview.setSelection(audit_id);
data.add(cc.getString("phone_name") +"\n\n"+cc.getString("audit_status") );
loadList(0);
btn_next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
increment++;
loadList(increment);
CheckEnable();
}
});
btn_prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
increment--;
loadList(increment);
CheckEnable();
}
});
//------------------------------------------------------------------------
}
}
pdLoading.dismiss();
//CheckEnable();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void loadList(int number)
{
ArrayList<String> sort = new ArrayList<String>();
title.setText("Page "+(number+1)+" of "+pageCount);
int start = number * NUM_ITEMS_PAGE;
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++)
{
if(i<data.size())
{
sort.add(data.get(i));
}
else
{
break;
}
}
sd = new ArrayAdapter<String>(Tblview.this,android.R.layout.simple_list_item_1,sort);
listview.setAdapter(sd);
}
private void CheckEnable()
{
if(increment+1 == pageCount)
{
btn_next.setEnabled(false);
btn_prev.setEnabled(true);
}
else if(increment == 0)
{
btn_prev.setEnabled(false);
btn_next.setEnabled(true);
}
else
{
btn_prev.setEnabled(true);
btn_next.setEnabled(true);
}
}
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int positon1 =position;
String a1 = Integer.toString(positon1);
Toast.makeText(getApplicationContext(),a1,Toast.LENGTH_SHORT).show();
}
});
If you are keeping count of page then you can add page number to item position.
That will give you unique number for each item.
I am using Thread for Webservice but i cant get the data from Thread because i cant return data from Thread.
This is my WebService.java :
public class Webservice {
static String result;
public static String readUrl(final String url) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
result = ConvertInputStreamToString(stream);
Log.i("xxx","OK" + result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return result;
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is NotesActivity.java :
public class NotesActivity extends Activity {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
thread.start();
}
}
This is my StructTask.java :
public class StructTask {
public long id;
public String title;
public String desc;
public boolean done;
}
This code return for me NULL .
Just try this way
1) Webservice.java
public class Webservice {
public interface WebCallListener{
void onCallComplete(String result);
}
public static void readUrl(final String url,final WebCallListener callListener) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
callListener.onCallComplete(ConvertInputStreamToString(stream));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
private static String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2) NotesActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Webservice.readUrl("http://192.168.200.101:8081/note-server/",new WebCallListener() {
#Override
public void onCallComplete(String result) {
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Log.i("OK", "TaskesOK: " + result);
Log.i("LOG", "Task: " + "NULL");
}
}
});
}
You may use your code some thing like this:
private class ImageDownloader extends AsyncTask {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return myBackgroundImageDownloadFun(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this,
"Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
MyImageView.setImageBitmap(result);
simpleWaitDialog.dismiss();
}
For this you can use AsyncTask i.e,
private class Webservice extends AsyncTask<Void, Void, ArrayList<StructTask>> {
private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<StructTask> doInBackground(Void... params) {
try {
String result = readUrl("http://192.168.200.101:8081/note-server/");
JSONArray tasks = new JSONArray(result);
for (int i = 0; i < tasks.length(); i++) {
JSONObject object = tasks.getJSONObject(i);
//Log.i("LOG", "Task: " + object.getString("task_title"));
StructTask task = new StructTask();
task.id = object.getLong("task_id");
task.title = object.getString("task_title");
task.desc = object.getString("task_desc");
task.done = object.getBoolean("task_done");
nettasks.add(task);
}
for (StructTask taskes : nettasks) {
Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nettasks;
}
/* after parsing response this method will be called*/
#Override
protected void onPostExecute(ArrayList<StructTask> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
private String readUrl(String url) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream stream = response.getEntity().getContent();
String result = ConvertInputStreamToString(stream);
Log.i("xxx", "OK" + result);
return result;
}
private String ConvertInputStreamToString(InputStream inputstteam) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputstteam));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
In your activity class in onCreate method try to call like this
Webservice service=new Webservice();
service.excute();
so it will starts the excution of the above thread.
i think this will helps you
When i am scrolling the GridView the images disappear in it. In log Cat its also showing outofmemory i dont know what i am doing wrong here.! It takes long time to display the images also. Thanks in Advance.
BaseActivity.java
public class BaseActivity extends Activity{
private Context context = this;
boolean server_connection = false;
static final Comparator<HashMap<String, String>> byDate = new Comparator<HashMap<String, String>>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
Date d1 = null;
Date d2 = null;
try {
if(ord1.get("datetime")!=null){
d1 = sdf.parse(ord1.get("datetime"));
}
else{
d1 = sdf.parse("1970-01-01 00:00:00");
}
if(ord2.get("datetime")!=null){
d2 = sdf.parse(ord2.get("datetime"));
}
else{
d2 = sdf.parse("1970-01-01 00:00:00");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("Date", ""+d1+"..........."+d2);
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<HashMap<String, String>> byCount = new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
int c1,c2;
if(ord1.get("download_count")!=null && !ord1.get("download_count").equals("null")){
c1=Integer.parseInt(ord1.get("download_count"));
}
else{c1=0;}
if(ord2.get("download_count")!=null && !ord2.get("download_count").equals("null")){
c2=Integer.parseInt(ord2.get("download_count"));
}
else{c2=0;}
return (c1>c2 ? -1 : 1); //descending
}
};
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public String prepareWebserviceRequest(String methodname, String[] keys, String[] values) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
for(int i=0;i<keys.length;i++){
json.put(keys[i],values[i]);
}
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public String prepareWebserviceRequestOnlyMethod(String methodname) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
// fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
class Download extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bmp=null;
bmp = getBitmapFromURL(params[0]);
return bmp;
}
}
public void WriteFile(String path,String filename,String data) {
try{
File direct = new File(path);
if(!direct.exists())
{
direct.mkdir();//directory is created;
}
String fpath= path +filename;
File txtfile=new File(fpath);
txtfile.createNewFile();
FileOutputStream fout=new FileOutputStream(txtfile);
OutputStreamWriter myoutwriter=new OutputStreamWriter(fout);
myoutwriter.write(data);
myoutwriter.close();
fout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public String ReadFile(String path,String filename)
{ File myFile = new File(path + filename);
if(!myFile.exists())
{
return null;
}
FileInputStream fIn = null;
try {
fIn = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
try {
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return aBuffer;
}
public boolean FileExist(String filename)
{
String PATH2 = Environment.getExternalStorageDirectory() + "/"+Constant.Alert_Name+filename;
Log.v("log_tag initial path", "PATH: " + PATH2);
File file2 = new File(PATH2);
if(file2.exists()==true)
{
return true;
}
return false;
}
public String callAPI(String strRequest) {
String result = null;
String new_params;
int ResponseCode;
// TODO Auto-generated method stub
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
//httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
httpParams.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
HttpClient client = new DefaultHttpClient(cm,httpParams);
String url = Constant.WebService_URL;
//String url = "http://192.168.1.3/messages_app/main.php";
URL url1 = new URL(Constant.WebService_URL);
// URL url1 = new URL("http://192.168.1.3/messages_app/main.php");
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
new_params =strRequest;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("json","{\"method_name\":\"get_all_category\"}"));
nameValuePairs.add(new BasicNameValuePair("json",new_params));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
ResponseCode = response.getStatusLine().getStatusCode();
//Log.d("ResponseCode", ""+ResponseCode);
if(ResponseCode==200){
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
result = RestClient.convertStreamToString(instream);
// Log.i("Read from server", result);
}
}
else if(ResponseCode!=200){
return "Server down";
}
} catch (Throwable t) {
return null;
}
return result;
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private String data[];
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
DisplayImageOptions options;
ArrayList<HashMap<String, String>> list;
public LazyAdapter(Activity a,ArrayList<HashMap<String, String>> list) {
this.list=list;
activity = a;
inflater = (LayoutInflater)LayoutInflater.from(a);
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "Download");
// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.memoryCacheExtraOptions(480,800)
.denyCacheImageMultipleSizesInMemory()
.discCacheExtraOptions(480, 480, CompressFormat.PNG, 100)
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
//imageLoader.init(ImageLoaderConfiguration.createDefault(a));
// imageLoader=new ImageLoader(activity.getApplicationContext());
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.cacheInMemory()
// .cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView==null)
{
vh = new ViewHolder();
convertView= inflater.inflate(R.layout.other, parent,false);
vh.iv=(ImageView)convertView.findViewById(R.id.picture);
vh.pb= (ProgressBar)convertView.findViewById(R.id.pb);
vh.tv = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
// vh.tv.setText("Image in postion ="+position);
if(Global.getCurrent_tab()==1){
vh.tv.setText(""+list.get(position).get("download_count"));
}
display(vh.iv, Constant.img_URL+list.get(position).get("photo_name"), vh.pb);
return convertView;
}
public void display(ImageView img, String url, final ProgressBar pb)
{
imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
#Override
public void onLoadingCancelled() {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(Bitmap arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(FailReason arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingStarted() {
// TODO Auto-generated method stub
pb.setVisibility(View.VISIBLE);
}
});
}
static class ViewHolder
{
ImageView iv;
TextView tv;
ProgressBar pb;
}
}
DefaultGridView.java
public class DefaultGridView extends Activity {
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new LazyAdapter(DefaultGridView.this,Global.getPhotos_list()));
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String url =Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name");
Intent i = new Intent(DefaultGridView.this, FullImageActivity.class);
i.putExtra("idkey", url); // pass the id
startActivity(i);
}
});
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setaswallpaper, reportissue;
String url1;
Bitmap myBitmap;
ImageDownloader mDownloader;
FileOutputStream fos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setaswallpaper = (Button) findViewById(R.id.setaswallpaper);
download = (Button)findViewById(R.id.download);
reportissue = (Button)findViewById(R.id.reportissue);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
url1 = getIntent().getStringExtra("idkey"); //get id
Log.i(".............",""+url1);
//imageView.setImageResource(id);
new Thread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
URL url = new URL(url1.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
}
catch(Exception e)
{
e.printStackTrace();
}
runOnUiThread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
imageView.setImageBitmap(myBitmap);
}
});
}
}).start();
setaswallpaper.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(myBitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
saveImageToSD();
// Toast.makeText(getApplicationContext(), "Wallpaper has been Downloaded...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
reportissue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Report Issue");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:reportissue#gmail.com")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);
}
});
}
private void saveImageToSD() {
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
long current = System.currentTimeMillis();
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + (current / 1000) + "wallpaper.jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am developing speech recognition for Java Application Using Sphinx 4. I want speech recognition for ANDroid. Please Help Me :)
//declearation
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
TextToSpeech talker;
//onCreate
Button speakButton=new Button(this);
talker = new TextToSpeech(this, this);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startVoiceRecognitionActivity();
}
});
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
//methods
/**
* Fire an intent to start the speech recognition activity.
*/
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
String device = "Bedroom";
String host = "http://web2.anzleads.com/Android/nimboPani/web-service.php?tmote=";
String userCommand = URLEncoder.encode(matches.get(0));
String deviceSelected = "&org=" + device;
res = getServerResponse(host + userCommand + deviceSelected);
say(""+ res);
}
super.onActivityResult(requestCode, resultCode, data);
}
public void say(String text2say){
talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status) {
// TODO Auto-generated method stub
// say("Hello World");
}
public void onDestroy() {
if (talker != null) {
talker.stop();
talker.shutdown();
}
super.onDestroy();
}
public String getServerResponse(String url)
{
String result = "";
HttpClient hc = new DefaultHttpClient();
HttpResponse hr ;
HttpGet hg = new HttpGet(url);
try
{
hr = hc.execute(hg);
if(hr.getStatusLine().getStatusCode() == 200)
{
HttpEntity he = hr.getEntity();
if (he != null)
{
InputStream is = he.getContent();
result = convertStreamToString(is);
is.close();
}
}
}
catch (Exception e) {
// TODO: handle exception
}
return result;
}
private String convertStreamToString(InputStream instream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I want to put bitmap images into ImageView of ListView. i changed image from url to bitmap image. I have 10 images and i have to put the images in each item of the ListView. Is there any method other than Lazy Adapter ?? Thanks in advance!!!
this is my code
public class Propertylist extends ListActivity {
String proptype;
String prop;
String estimate;
String photo;
String get;
String[] data;
TextView text;
URL aURL;
InputStream is = null;
String result = "";
JSONObject jArray = null;
//Hashtable<String,Bitmap> imagemap;
private ArrayList<NameValuePair> nameValuePairs;
private LayoutInflater inflater;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
text = (TextView) findViewById(R.id.text);
Toast.makeText(getApplicationContext(), "Displaying popertylist for zipcode "+get, Toast.LENGTH_LONG).show();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//ArrayList<Hashtable<String, Bitmap>> mylist1 = new ArrayList<Hashtable<String, Bitmap>>();
Bundle bundle = this.getIntent().getExtras();
get = bundle.getString("name");
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.propertyhookup.com/mobile/propertylist.php");
nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("zipcode", get.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
if(result.length()<= 7){
Toast.makeText(getApplicationContext(), "No properties for this zipcode or check your zipcode ", Toast.LENGTH_LONG).show();
text.setText("No properties for this zipcode or check your zipcode");
}
else{
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
//JSONObject json = JSONfunctions.getJSONfromURL("http://192.168.1.111/propertyhookup.com/mobile/propertylist.php");
try{
JSONArray earthquakes = jArray.getJSONArray("earthquakes");
for(int i=0;i<10;i++){
HashMap<String, String> map = new HashMap<String, String>();
//imagemap = new Hashtable<String, Bitmap>();
JSONObject e = earthquakes.getJSONObject(i);
if(e.getString("property_type").contains("1")) {
proptype ="Single Family Home";
}else if(e.getString("property_type").contains("2")) {
proptype="Condo";
}else if(e.getString("property_type").contains("3")) {
proptype="Townhouse";
}
if(e.getString("estimated_price").contains("0")) {
estimate = "Not Enough Market Value";
//estimat = (TextView) findViewById(R.id.estimat);
//estimat.setTextColor(Color.rgb(0, 0, 23));
}else {
estimate = "$"+e.getString("estimated_price");
}
photo = e.getString("photo1");
map.put("id", String.valueOf(i));
map.put("percent", e.getString("percentage_depreciation_value")+"%");
map.put("propertyid", "#"+e.getString("property_id")+" ");
map.put("cityname",e.getString("city_name")+",");
map.put("statecode",e.getString("state_code"));
map.put("propertytype","| "+ proptype);
map.put("footage", e.getString("house_square_footage")+" Sq.Ft");
map.put("bathroom", "| "+e.getString("bathrooms")+" Bath, ");
map.put("bedroom", e.getString("bathrooms")+" Bedrooms");
map.put("price", "List Price: $"+e.getString("property_price"));
map.put("estimated", "Base Market Value: "+estimate);
//map.put("photos",photo );
mylist.add(map);
}
}catch(JSONException e) {
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
try
{
aURL = new URL(photo);
}
catch (MalformedURLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection conn = null;
try
{
conn = aURL.openConnection();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
conn.connect();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is = null;
try
{
is = conn.getInputStream();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedInputStream bis = new
BufferedInputStream(is,8*1024);
Bitmap bm = BitmapFactory.decodeStream(bis);
//imagemap.put("im",bm);
// mylist1.add(imagemap);
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main4,
new String[] { "percent","propertyid", "cityname", "statecode", "propertytype", "footage", "bathroom", "bedroom", "price", "estimated" },
new int[] { R.id.percent, R.id.property_id, R.id.city_name, R.id.state_code, R.id.prop_type, R.id.foot, R.id.bath, R.id.bed, R.id.list, R.id.estimat});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Propertylist.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon: //Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
displaylogin();
break;
case R.id.text: //Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
displayproperty();
break;
// case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
// break;
}
return true;
}
private void displaylogin() {
startActivity(new Intent(this,Changezip.class));
finish();
}
private void displayproperty() {
startActivity(new Intent(this,property.class));
}
}
You might want to check out the GreenDroid library; it makes doing things like this trivial.
Please note that you have asked 4 previous questions that received answers and you have not accepted any of them. This community functions based on people accepting answers and if you don't start accepting answers you've found useful, you may find that people stop answering you.