Hi I have one problem with ProgressDailog. I'm not able to set it properly in my code. In my code I'm getting URLs of images through JSON Array and downloading that images after that showing them into GridView and on click displaying selected image on next activity..This all work perfectly but the problem is As I'm using AsyncTask in my code it goes in background and fetch JSON, download images. I want to show ProgressBar till background process is completed and initialize the GridView after all images get downloaded ...
Following is my code..
public class AndroidGridLayoutActivity extends Activity {
public static ImageAdapter img;
public static String[] imageurls;
public static GridView gridView;
public static Bitmap bm[]=new Bitmap[4];
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
// Showing progress dialog
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
new GetImageUrls().execute();
Thread thread = new Thread()
{
#Override
public void run() {
int count=0;
while(count<3) {
try {
sleep(1000);
count++;
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
if(pDialog != null && pDialog.isShowing()){
pDialog.dismiss();
}
new GetImageUrls().execute();
}
};
thread.start();
gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
img = new ImageAdapter(AndroidGridLayoutActivity.this,bm);
gridView.setAdapter(img);
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
Log.d("DownloadImage: ", url.toString());
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
Log.d("DownloadImage response: ", Integer.toString(response));
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("DownloadImage: ", in.toString());
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
Log.d("DownloadImage Bitmap: ", bitmap.toString());
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
}
As I run this code the images get downloaded but not display on grid view and as I click on any Grid the image displays on next activity,,
ImageAdapter Class:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public static Bitmap adapterbm[]=new Bitmap[4];
ImageView imageView;
public static String[] imageurls;
// Constructor
public ImageAdapter(Context c, Bitmap[] bm){
mContext = c;
adapterbm = bm;
}
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return adapterbm.length;
}
#Override
public Object getItem(int position) {
return adapterbm[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imageView = new ImageView(mContext);
imageView.setImageBitmap(adapterbm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
You should Override onPreExecute() method before doInBackground method.
ProgressDialog myPd_bar;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(AndroidGridLayoutActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(title);
myPd_bar.show();
super.onPreExecute();
}
Then you should Override onPostExecute() method after doInBackground method.
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
myPd_bar.dismiss();
}
You can find more information from this link
Place your ProgressDialog in onPreExecute, hope this code helps you out :)
private ProgressDialog pdia;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
There are two more method in Async class i.e onPostExecute and onPreExecute method. in onPreExecute method you can write the following code
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
And onPostExecute method use pDialog.dismiss().
Use preExcecute to display progress dialog.
ProgressDialog pDialog;
public class GetImageUrls extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg)
{....
}
#Override
protected postExcecute()
{
pDialog.dismiss();
....//display UI
...
}
There is no need of writing Thread to show ProgressDialog.
Just simply you need to implement onPreExecute to show the dialog and onPostExecute to dismiss the dialog.
Just change your GetImageUrls method as below:
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(this);
pDialog.setMax(5);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
Start dialog in
onPreExecute()
and dismiss it
onPostExecute()
The easiest way to show progress while doing background process!
private class GetImageUrls extends AsyncTask<String, String , String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(this,null, "Loading ...", true);
progressDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... arg0) {
//background process
}
protected void onProgressUpdate(String... str) {
}
protected void onPostExecute(String result) {
progressDialog.dismiss(); // once process complete it will dismiss.
}
}
Use beelow code:
ProgressDialog mProgressDialog;
public class GetImageUrls extends AsyncTask<Void, Void, Void>
{
Context context = getBaseContext();
private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
private static final String MAIN = "mainCategory";
private static final String SUB = "mcatimage";
JSONArray loginjsonarray=null;
#Override
protected void onPreExecute(){
super.onPreExecute();
mProgressDialog = ProgressDialog.show(AndroidGridLayoutActivity.this,
"", "Loading...");
mProgressDialog.setCancelable(false);
}
protected Void doInBackground(Void... arg) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
if(jsonstr!=null)
{
try {
JSONObject jsonObj =new JSONObject(jsonstr);
loginjsonarray=jsonObj.getJSONArray(MAIN);
imageurls=new String[loginjsonarray.length()];
for(int i=0;i<loginjsonarray.length();i++)
{
JSONObject l=loginjsonarray.getJSONObject(i);
imageurls[i]=l.getString(SUB);
}
for(int i=0;i<imageurls.length;i++)
{
bm[i]=DownloadImage(imageurls[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
}
return null;
}
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
Log.d("DownloadImage: ", url.toString());
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
Log.d("DownloadImage response: ", Integer.toString(response));
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
Log.d("DownloadImage: ", in.toString());
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
Log.d("DownloadImage Bitmap: ", bitmap.toString());
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
#Override
protected void onPostExecute(){
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
}
Try this
Activity class
package com.example.imagelist;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ItemsAdapter adapter;
ListView list;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://........................";
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion > android.os.Build.VERSION_CODES.FROYO) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
}
/*
int images[] = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
*/
list = (ListView) findViewById(R.id.listView1);
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar=new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = 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(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
myPd_bar.dismiss();
}
}// 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 ListDrwaer(){
List<String> listImg = new ArrayList<String>();
try{
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
listImg.add(img_url);
// Log.d("URL", img_url);
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(), listImg);
list.setAdapter(adapter);
}
catch(JSONException e){
Toast.makeText(getApplicationContext(),"Connection Error...", Toast.LENGTH_LONG).show();
}
}
}
Adapter class
package com.example.imagelist;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class ItemsAdapter extends ArrayAdapter<Integer> {
private final Context context;
ImageView imageView;
List<String> listImg;
ItemsAdapter(Context context, List<String> listImg) {
super(context, R.layout.items_list_item);
this.context = context;
this.listImg = listImg;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listImg.size();
}
#Override
public Integer getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final String text = listImg.get(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
if (null == convertView)
rowView = inflater.inflate(R.layout.items_list_item, parent, false);
imageView = (ImageView) rowView.findViewById(R.id.list_item_image);
Bitmap bitmap;
URL imageURL = null;
try {
imageURL = new URL(text);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return rowView ;
}
}
activity_main.xml
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
list_item.xml
<ImageView
android:id="#+id/list_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
you can use gridView instead of listview.
Use onPreExecute and onPostExecute method
Related
I am new for Android i want to know how to connect database.I saw one video in you tube and i follow hole video but its not working.i don't know where i made mistake. please help me.from one week an words i'm trying but now also i'm not getting solution please help me stack over flow.
class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT=1000*15;
public static final String
SERVER_ADDRESS="http://192.168.1.11/myfolder/new1.php";
public ServerRequests(Context context){
progressDialog=new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("processing");
progressDialog.setMessage("please wait.....");
}
public void storeUserDataInBackground(User user,GetUserCallbackuserCallback{
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("name",user.name));
dataToSend.add(new BasicNameValuePair("age",user.age + ""));
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(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(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 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(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponce httpResponce=client.execute(post);
HttpEntity entity=httpResponce.getEntity();
String result= EntityUtils.toString(entity);
JSONObject jObject=new JSONObject(result);
if (jObject.length()==0){
user=null;
}else{
String name=jObject.getString("name");
int age =jObject.getInt("age");
returnedUser=new User(name,age,user.username,user.password);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(User returnedUser){
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(returnedUser);
}
}
}
enter code here
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText etusername,etpassword;
TextView tvregister;
UserLocalStore userLocalStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etusername=(EditText)findViewById(R.id.username_edit);
etpassword=(EditText)findViewById(R.id.password_edit);
blogin=(Button)findViewById(R.id.login_button);
tvregister=(TextView)findViewById(R.id.tv_register);
blogin.setOnClickListener(this);
tvregister.setOnClickListener(this);
userLocalStore=new UserLocalStore(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login_button:
String username=etusername.getText().toString();
String password=etpassword.getText().toString();
User user=new User(username,password);
authenticate(user);
userLocalStore.storeUserData(user);
userLocalStore.setUserLoggedIn(true);
break;
case R.id.tv_register:
startActivity(new Intent(this,RegisterActivity.class));
break;
}
}
private void authenticate(User user) {
ServerRequests serverRequests = new ServerRequests(this);
serverRequests.fetchUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
if (returnedUser == null) {
showErrorMessage();
}else {
logUserIn(returnedUser);
}
}
});
}
private void showErrorMessage() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LoginActivity.this);
dialogBuilder.setMessage("Incorrect user details");
dialogBuilder.setPositiveButton("ok", null);
dialogBuilder.show();
}
private void logUserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
startActivity(new Intent(this,MainActivity.class));
}
}
Here is the link which you can refer for fetching data from server.
For Creating Web Service using PHP Click here
<?php
include("connect.php");
$result="";
//get data from users (name for user variable is p1 and p2
//here I am stroing this value to par1 and par2
//method i am using is GET
$par1=$_GET['p1'];
$par2=$_GET['p2'];
$eve = "select * from table where field1='$par1' and field2='$par2'";
$re = mysql_query($eve);
$response = array();
$posts = array();
while($rt = mysql_fetch_array($re))
{
$f1=$rt['field1'];
$f2=$rt['field2'];
break;
}
$posts[] = array('p1'=> $f1,'p2'=> $f2);
$response['posts'] = $posts;
echo stripslashes(json_encode( array('item' => $posts)));
?>
For AsyncTask Example Click here
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Login extends AppCompatActivity {
boolean remember;
private ProgressDialog pDialog;
public static final String PREFS_NAME = "Preference";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
((Button) findViewById(R.id.btnlogin)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Login Validation
try {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Verifying...");
pDialog.show();
LoginVerifyTask g = new LoginVerifyTask();
g.execute(((EditText) findViewById(R.id.mobile)).getText().toString(), ((EditText) findViewById(R.id.password)).getText().toString());
} catch (Exception e) {
Log.e("cs", "catch error");
}
}
});
((TextView) findViewById(R.id.newuserregistrationtxtview)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Registration1.class);
startActivity(i);
}
});
}
public class LoginVerifyTask extends AsyncTask<String, Void, String>
{
String u,p;
void LoginActivity(String s)
{
}
#Override
protected void onPostExecute(String json) {
// TODO Auto-generated method stub
pDialog.dismiss();
pDialog = null;
if (json == null)
{
return;
}
String csv="";
try {
JSONObject js = new JSONObject(json);
JSONArray user = js.getJSONArray("item");
for(int i=0;i<user.length();i++)
{
JSONObject j2 = user.getJSONObject(i);
//received data
String result = j2.get("p1").toString();
break;
}
}
catch(JSONException js)
{
}
return;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
u = params[0];
p = params[1];
String tempdata="";
String buffer="";
try
{
URL url = new URL("http://websitename.com/folder/webservice.php?p1=" + params[0].replace(" ", "%20") + "&p2=" + params[1].replace(" ", "%20"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
//buffer = new String();
if(is==null)
{
return tempdata;
}
else
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line="";
while( (line = reader.readLine())!=null)
{
buffer += line;
}
return buffer;
}
}
catch(Exception e)
{
Log.e("cs", e.toString());
}
return buffer;
}
}
}
Hi I have a JSON Data and I'm getting it through url by using get method,I need to show the sender,receiver,message in Textview,I have created a JsonParser class also but after running the app its showing Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference.How to fix this issue.
Here is what I have tried
private static String url = "http://130.211.99.188/api/messages";
JSONArray _items = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView1);
t2 = (TextView)findViewById(R.id.textView2);
t2 = (TextView)findViewById(R.id.textView3);
if (Utils.isNetConnected(this))
{
new Parser().execute();
}
else
Utils.showDialog(this);
}
class Parser extends AsyncTask < String, String, String > {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONData(url);
try{
_items = json.getJSONArray("_updated");
for(int i=0;i<_items.length();i++){
JSONObject object = _items.getJSONObject(i);
sender = object.getString("sender");
receiver = object.getString("receiver");
message = object.getString("message");
}
}catch(JSONException e){
e.printStackTrace();
}
return message;
}//Ending doInBackground
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
t1.setText(sender);
t2.setText(receiver);
t3.setText(message);
}
}
}
This is my JSON Data
{"_items": [{"_updated": "Thu, 01 Jan 1970 00:00:00 GMT", "sender": "556a1233aca33b3c8158de0a", "timestamp": 1433018976, "receiver": "5569c6c5aca33b3c8158de07", "_links": {"self": {"href": "messages/556a2260aca33b3c8158de11", "title": "messages"}}, "message_created": "Sat, 30 May 2015 20:49:36 GMT", "seen": false, "message": "hii", "_id": "556a2260aca33b3c8158de11", "_etag": "afa4fe57efec9abf7c5bc817a7e045a5b4467384", "_created": "Thu, 01 Jan 1970 00:00:00 GMT"},
This is the complete code, have a look at the data printed
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends Activity {
ProgressDialog pdialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new postServer().execute();
}
public String postData() throws JSONException {
// Create a new HttpClient and Post Header
String downloadedString = null;
HttpClient httpclient = new DefaultHttpClient();
// for registerhttps://te
// HttpPost httppost = new HttpPost("http://130.211.99.188/api/messages");
HttpClient myClient = new DefaultHttpClient();
// HttpPost myConnection = new HttpGet("http://130.211.99.188/api/messages");
try {
// HttpResponse response = myClient.execute(myConnection);
HttpResponse httpResponse = httpclient.execute(new HttpGet("http://130.211.99.188/api/messages"));
downloadedString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("downloadedString:in login:::"
+ downloadedString);
return downloadedString;
}
public class postServer extends AsyncTask<Void, Void, Void> {
String jsonstring = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setCancelable(false);
pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pdialog.setMessage("Loading..");
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
jsonstring = postData();
} catch (JSONException 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 {
if(pdialog!=null){
pdialog.dismiss();
}
JSONObject mainObject = new JSONObject(jsonstring);
JSONArray array=mainObject.getJSONArray("_items");
for(int i=0;i<array.length();i++){
System.out.println(array.getJSONObject(i).getString("sender"));
System.out.println(array.getJSONObject(i).getString("receiver"));
System.out.println(array.getJSONObject(i).getString("message"));
}
} catch (Exception e) {
// TODO: handle exception
if (pdialog != null) {
pdialog.dismiss();
}
System.out.println(e.getMessage());
}
}
}
}
Thanks
Have you tried just declaring the JSONArray variable without assigning it a null value? JSONArray _items;
_items = json.getJSONArray("_updated");
Change to
_items = json.getJSONArray("_items");
And
class Parser extends AsyncTask < String, String, String > {
to
class Parser extends AsyncTask < void, void, void > {
Try this code:
class Parser extends AsyncTask < String, String, String > {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONData(url);
try{
_items = json.getJSONArray("_items");
for(int i=0; i<_items.length(); i++){
JSONObject object = _items.getJSONObject(i);
sender = object.optString("sender");
receiver = object.optString("receiver");
message = object.optString("message");
}
}
catch(JSONException e){
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
t1.setText(sender);
t2.setText(receiver);
t3.setText(message);
}
}
Try to use optString() instead of getString() because the former returns null if doesn't exist and it doesn't throw an exception
Are you sure getJSONData(url) in JSONObject json = jParser.getJSONData(url); is not returning null?
Your question indicates that you are calling getJSONArray() on a null object. Which means the JSON object you queried from the parser is null
I am trying to use a thread to do some work in the background which takes a few seconds.
I was trying to display a progress dialog but its not displaying at all.
I thought it would be better to use an Async task but whenever I try I cannot get it to work, mostly because I cannot access the variables I need to modify within the Async task.
Here is my thread which is called when a button is clicked:
Thread thread = new Thread()
{
#Override
public void run() {
try {
for (String s : dLinks) {
String pathToFile = s.substring(1));
dURLs.add(dFs.fetchLink(pathToFile, false).toString());
}
} catch (DbxException e) {
dURL = null;
e.printStackTrace();
}
}
};
thread.start();
try {
thread.join(); // I added this as the next part of my code was executing before the thread was finished
} catch (InterruptedException e) {
e.printStackTrace();
}
Could I move this to an Async task, update a progress bar or at least show a spinner AND pass back the array dURLs to the Main thread?
Here we called AsyncTask with activity's context this which will feed to AsyncTask to show ProgressDialog in these Activity while AsyncTask runs in background.
public void onCreate(Bundle savedInstanceState)
{
SpinnerDataTask spinnerDataTask = new SpinnerDataTask(this);
spinnerDataTask.execute(null);
}
AsyncTask has method which uses to do background work in doInBackground() and post the result in onPostExecute(). To show view whenever AsyncTask start working, onPreExecute() is perfect to show that something is working in background.
private class SpinnerDataTask extends AsyncTask<Void Void, Void>
{
Context context;
public SpinnerDataTask(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
for (String s : dLinks) {
String pathToFile = s.substring(1));
dURLs.add(dFs.fetchLink(pathToFile, false).toString());
}
} catch (DbxException e) {
dURL = null;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pDialog.isShowing())
{
pDialog.dismiss();
}
}
}
you can use like this:
public class web_api_get_thread extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(context);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.show();
progressDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
StringBuilder builder = new StringBuilder();
//do your work
return builder.toString();
} // protected Void doInBackground(String... params)
protected void onPostExecute(String string) {
this.progressDialog.dismiss();
// see your result here
}
}
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import de.vogella.android.asyntask.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class ReadWebpageAsyncTask extends Activity {
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.TextView01);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
}
}
Create the following layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/readWebpage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Load Webpage" >
</Button>
<TextView
android:id="#+id/TextView01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Placeholder" >
</TextView>
</LinearLayout>
refer to :http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
I want to add progress bar to android project to show upload files. here is my code for upload images to server. postFile() is working fine. How to visible progress bar?
I want to add progressbar here.pleas see this code in the class
//Progrssbar Visible here
postFile();
//Progrssbar Invisible here
Here is the class
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
public String DataSendingTo="http://www.mysite.com/receiver.php/Incoming_Data_Receive";
public String txtDescription;
public static String[] FileNameStrings = new String[8];
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... strings) {
try
{
//Progrssbar Visible here
postFile();
//Progrssbar Invisible here
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
private void postFile(){
try{
// the file to be posted
for(int f=0;f <FileNameStrings.length;f++)
{
String textFile = FileNameStrings[f];
if(textFile==null)
{
break;
}
Log.v("Sending", "textFile: " + textFile);
// the URL where the file will be posted
Log.v("Sending", "postURL: " + DataSendingTo);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(DataSendingTo);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("Sending", "Response: " + responseStr);
//wait(1500);
}
}
} catch (NullPointerException e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:1 on uplod file", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getBaseContext(), "Error:2 File may be already exists", Toast.LENGTH_LONG).show();
}
}
}
Add below code to your AsyncTask
class PostDataAsyncTask extends AsyncTask<String, String, String> {
private ProgressDialog mDialog = null;
public PostDataAsyncTask(Context activityContext) {
mDialog = new ProgressDialog(activityContext);
}
protected void onPreExecute() {
super.onPreExecute();
mDialog.setMessage("Wait...");
mDialog.setCancelable(false); // Depends on app behaviour
mDialog.show();
}
#Override
protected String doInBackground(String... strings) {
// Same as your implementation
}
#Override
protected void onPostExecute(String lenghtOfFile) {
if (mDialog != null)
mDialog.dismiss();
}
}
And call this as
PostDataAsyncTask postDataAsyncTask = new PostDataAsyncTask(Youractivity_name.this);
postDataAsyncTask.execute(With_your_params);
you can se ein this example just call progressdialog in onPreExecute() method.,and refer this example.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** Reference to the view which should receive the image */
private final WeakReference imageRef;public DownloadImageTask(ImageView imageView) {
imageRef = new WeakReference(imageView);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(DownloadImageActivity.this, "Wait", "Downloading...");
}
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
URL url = new URL(params[0]);
// We open the connection
URLConnection conection = url.openConnection();
conection.connect();
input = new BufferedInputStream(url.openStream(), 8192);
// we convert the inputStream into bitmap
bitmap = BitmapFactory.decodeStream(input);
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return bitmap;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(Bitmap bitmap) {
progressDialog.dismiss();
if (isCancelled()) {
bitmap = null;
}
if (imageRef != null) {
ImageView imageView = imageRef.get();
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
} else
Toast.makeText(DownloadImageActivity.this, "Error while downloading the image!", Toast.LENGTH_LONG).show();
}
}
}
I 'm having a problem with my gallery, it's to slow and it lags. I 'm loading images from server with Image Adapter:
package com.example.ocenitaksi;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.mobile, null);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
// ubacivanje slika za string
String mobile = mobileValues[position];
if (mobile.equals(MainActivity.imena[position])) {
//imageView.setImageURI("http://24.media.tumblr.com/avatar_a400b4dbb80e_64.png");
Bitmap bitmap=null;;
mobile = mobile.replace(" ", "_");
bitmap = DownloadImage("http://android.yunews.net/images/"+mobile+".png");
imageView.setImageBitmap(bitmap);
}
}
else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return mobileValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
and this is part of my main activity.
private class LongOperation extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Molimo sacekajte...");
progressDialog.setMessage("Ucitavam taksi sluzbe...");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected String doInBackground(String... params)
{
niz = new JSONFunkcije().ListaSluzbi();
imena= new String[niz.size()];
Iterator<String> it= niz.iterator();
for (int i=0;i<niz.size();i++)
imena[i]=it.next();
slicice = new ImageAdapter(MainActivity.this, imena);
return null;
}
protected void onPostExecute(String result)
{
progressDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
//Button dugme1 = (Button) findViewById(R.id.dugme1);
///params.height = "50dpi";
//dugme1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 100));
Gallery gridView = (Gallery) findViewById(R.id.gallery1);
gridView.setAdapter(slicice);
//kraj ucitvanja
//gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), TaksiDetalji.class);
// passing array index
i.putExtra("id", imena[position]);
startActivity(i);
}
});
}
});
System.gc();
}
}
I 'm calling LongOperation from OnCrate:
mytask = new LongOperation();
mytask.execute();
Is something wrong with ImageAdapter? Too many calls, downloads? I tried to cache images but I failed.
From your code, I would say there are many reasons and because all these below reasons its running slow:
You haven't followed ViewHolder pattern. Read documentation also for Making ListView Scrolling Smooth
You haven't followed standard way of loading images (i.e. Cached images in local, load from local if its already cached)
Better you try any library available (Universal Image loader or any) on web to load images in your ListView.