Android - get photos from database with AsyncTask - doInBackGround not starting - android

I'm having a problem with my program. I'm calling my getImages() function in onCreate() but when I tried debugging it, I discovered that doInBackground() function doesn't actually start. I've seen many people had the same problem but none of the solutions provided were of any help.
Here is how my main activity looks like:
public class poi_photos extends ActionBarActivity {
public static ArrayList<String> image_urls = new ArrayList<>();
public static GridView gridView;
// Retrieve PHOTOS from database
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_EMAIL_USER = "email_user";
private static final String TAG_POI_NAME = "poi_name";
private static final String TAG_PHOTO_URL = "photo_url";
JSONArray photos = null;
ArrayList<HashMap<String, String>> photoList;
ArrayList<HashMap<String, Integer>> numsList;
// GALLERY
private FeatureCoverFlow mCoverFlow;
private CoverFlowAdapter Adapter;
private ArrayList<GameEntity> mData = new ArrayList<>(0);
private TextSwitcher mTitle;
String photo_url2;
// Camera Activity
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
static int TAKE_PICTURE = 1;
// MENU
String TITLES[] = {"Home", "Profile", "Travel", "POIs Map", "Find your friends!", "Take Picture"};
int ICONS[] = {R.drawable.ic_home, R.drawable.ic_prof, R.drawable.ic_travel, R.drawable.ic_poi, R.drawable.ic_friends_map, R.drawable.ic_photo};
String NAME = MainActivity.username;
String EMAIL = MainActivity.user_email;
private Toolbar toolbar; // Declaring the Toolbar Object
RecyclerView mRecyclerView; // Declaring RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_photos);
FloatingActionButton add_comment = (FloatingActionButton) findViewById(R.id.button_poi_comments);
add_comment.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
add_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(poi_photos.this, MarkerActivity.class));
}
});
FloatingActionButton see_photos = (FloatingActionButton) findViewById(R.id.button_add_photo);
see_photos.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
see_photos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takepic();
}
});
image_urls.clear();
if (image_urls.isEmpty())
{
getImages();
}
gridView = (GridView) findViewById(R.id.gridview);
final ImageAdapter adapter = new ImageAdapter(this);
// adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(poi_photos.this, ImageActivity.class);
intent.putExtra("url", adapter.imageUrls.get(position));
startActivity(intent);
}
});
// MENU
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES, ICONS, NAME, EMAIL, this); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
final GestureDetector mGestureDetector = new GestureDetector(poi_photos.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
Drawer.closeDrawers();
// Toast.makeText(map.this,"The Item Clicked is: "+recyclerView.getChildPosition(child),Toast.LENGTH_SHORT).show();
switch (recyclerView.getChildPosition(child)) {
case 1:
Intent a = new Intent(poi_photos.this, myprofile.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(poi_photos.this, profile.class);
startActivity(b);
break;
case 3:
Intent c = new Intent(poi_photos.this, ShortPath.class);
startActivity(c);
break;
case 5:
Intent e = new Intent(poi_photos.this, FriendsMap.class);
startActivity(e);
break;
case 6:
//Camera Activity
if (hasCamera()) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
break;
}
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this, Drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_poi_photos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// method to check if you have a Camera
private boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
// CAMERA ACTIVITY
private void takepic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
// Show pop up window
LayoutInflater layoutInflater = LayoutInflater.from(poi_photos.this);
View promptView = layoutInflater.inflate(R.layout.input_photo, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(poi_photos.this);
alertDialogBuilder.setView(promptView);
ImageView imageView = (ImageView) promptView.findViewById(R.id.imageView_photo);
imageView.setImageBitmap(photo);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Keep the photo!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
upload(); // upload photo to folder
upload2(); // upload photo to database
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
// upload photo to database
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(poi_photos.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait uploading image!");
pd.show();
}
// insert photo
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
photo_url2 = map.markername + "_" + System.currentTimeMillis() + ".jpg";
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", photo_url2));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/photo.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop " + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
// insert photo
private void upload2() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email_user", MainActivity.user_email));
nameValuePairs.add(new BasicNameValuePair("poi_name", map.markername));
nameValuePairs.add(new BasicNameValuePair("photo_url", photo_url2));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http:xxxxx/photo_out.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data has been sent successfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Log.e("ClientProtocol", "Log_Tag");
e.printStackTrace();
String msg2 = "Log_Tag";
Toast.makeText(getApplicationContext(), msg2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("Log_Tag", "IOException");
e.printStackTrace();
String msg3 = "IOException";
Toast.makeText(getApplicationContext(), msg3, Toast.LENGTH_LONG).show();
}
}
// GETTING PHOTOS FROM DATABASE
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
photos = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < photos.length(); i++) {
JSONObject c = photos.getJSONObject(i);
String email_user = c.getString(TAG_EMAIL_USER);
String poi_name = c.getString(TAG_POI_NAME);
String photo_url = c.getString(TAG_PHOTO_URL);
if ((poi_name.substring(0, 4)).equals(map.markername) && photo_url!=null) {
// add to the picasso gallery
photo_url="http://romcad.ro/poi/photos/"+photo_url;
image_urls.add(photo_url);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getImages() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxxxx/table_photo_out.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
Any idea/ tip what might be the problem here?

Why do you write the class GetDataJSON into the method getImages()?
Try to delete the method around your class and instead of calling getImages() call
new getDataJSON().execute(yourString);

Related

I need to set my app content offline

I am getting my content from json through server.I have two TextView and one ImageView in my layout.i have written the content from json to a file. but i not able to set my data while offline
I am getting the data from a file also.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Context context;
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
NewsAdapter adapter;
ArrayList<News> Newslist;
private Toolbar mToolbar;
private ProgressDialog pDialog;
private String TAG = MainActivity.class.getSimpleName();
private static String url = "https://www.amrita.edu/amrita_api/v1/news_android.jsonp";
String image;
String imageurl;
ArrayList<HashMap<String, String>> arraylist;
// ArrayList<String> newsList = new ArrayList<String>();
WebView descWView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_json);
Newslist = new ArrayList<News>();
context=getApplicationContext();
//initViews();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(R.string.title);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.app_icon);
initViews();
initContentWebView();
setUpNavDrawer();
new GetContacts().execute();
}
private void initViews(){
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
}
void initContentWebView(){
String htmlText = " %s ";
// ArrayList<String> myData = newsList;
// descWView = (WebView) findViewById(R.id.content_wview);
// String htmlData= "<html><body style='text-align:justify;font-size:"+getResources().getInteger(R.integer.main_text)+"px'><p>'sajhdsakjc;osalcjklsx'</p>"+myData.toString()+"</body></Html >";
//descWView.getSettings().setDefaultTextEncodingName("utf-8");
// descWView.loadData(htmlData, "text/html", "utf-8");
// descWView.loadDataWithBaseURL(String.format(htmlText, htmlData), String.valueOf(myData), "text/html", "UTF-8", String.format(htmlText, htmlData));
// descWView.s(myData);
}
private void setUpNavDrawer() {
mDrawerToggle=new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.drawer_open,R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(this);
}
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
String item=menuItem.getTitle().toString();
String dPath=menuItem.getTitleCondensed().toString();
if(item.equals("News")){
//this.finish();
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
this.finish();
//Toast.makeText(getApplicationContext(), "god", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Events")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, EventActivity.class);
startActivity(intent);
this.finish();
Toast.makeText(getApplicationContext(), "god1", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Latest Publications")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god2", Toast.LENGTH_SHORT).show();
} else if(item.equals("Students Achivements")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god3", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Important Announcements")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god4", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Research")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, ResearchActivity.class);
startActivity(intent);
this.finish();
//Toast.makeText(getApplicationContext(), "god5", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Ranking")){
mDrawerLayout.closeDrawers();
//Toast.makeText(getApplicationContext(), "god6", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, RankingActivity.class);
startActivity(intent);
this.finish();
}
else if(item.equals("International")){
mDrawerLayout.closeDrawers();
//Toast.makeText(getApplicationContext(), "god7", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, InternationalActivity.class);
startActivity(intent);
this.finish();
}
else if(item.equals("About")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, AboutActivity.class);
startActivity(intent);
this.finish();
// Toast.makeText(getApplicationContext(), "god8", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Contact Us")) {
mDrawerLayout.closeDrawers();
// Toast.makeText(getApplicationContext(), "god9", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ContactUs.class);
intent.putExtra("keyId", item);
intent.putExtra("descPath",dPath);
startActivity(intent);
// this.finish();
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_share) {
/*Intent intent=new Intent(context,AboutActivity.class);
startActivity(intent);
return true;*/ Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// arraylist = new ArrayList<HashMap<String, String>>();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(jsonStr);
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
News news = new News();
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONObject jsonimage=jsonobject.getJSONObject("image");
//Log.d(String.valueOf(jsonimage), String.valueOf(jsonimage.length()));
String imageurl=jsonimage.getString("filename");
// System.out.println(imageurl);
// Retrive JSON Objects
news.setTitle(jsonobject.getString("title"));
news.setBody(jsonobject.getString("body"));
// news.setImage(jsonobject.getString("image"));
news.setImage(jsonimage.getString("filename"));
// Set the JSON Objects into the array
Newslist.add(news);
/*image = jsonobject.getString("image");
String title = jsonobject.getString("title");
String content = jsonobject.getString("content");
newsList.add(image);
newsList.add(title);
newsList.add(content);*/
// Log.d(newsList.get(i),"image");
// Log.d(title,"title");
// System.out.println("All MinQuantitiy"+newsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
/* try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d(jsonStr,"json");
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("news");
// looping through All Contacts
*//*for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}*//*
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}*/
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
int sizeofarray= Newslist.size();
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(context,sizeofarray ));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
TextView tvtitle=(TextView)findViewById(R.id.tvtitle);
TextView tvbody=(TextView)findViewById(R.id.tvbody);
ImageView im=(ImageView)findViewById(R.id.NewsImage);
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
for(position=0;position<20;position++) {
tvtitle.setText(Newslist.get(position).getTitle());
tvbody.setText(Newslist.get(position).getBody());
// Toast.makeText(getApplicationContext(),position//, Toast.LENGTH_LONG).show();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// im.setImageResource(String.format("https://www.amrita.edu/sites/default/files/%s", Newslist.get().getImage()));
Toast.makeText(getApplicationContext(),"sizeNewslist"+sizeofarray, Toast.LENGTH_LONG).show();
// Updating parsed JSON data into ListView
/*for(int i=1;i<3;i++){
Toast.makeText(getApplicationContext(),
"aaa"+newsLists,
Toast.LENGTH_LONG)
.show();
}*/
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, newsList,
R.layout.list_item, new String[]{"name", "email",
"content"}, new int[]{R.id.image,
R.id.title, R.id.co});
lv.setAdapter(adapter);*/
}
}
}
/* public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}*/
adapter class
public class CustomPagerAdapter extends PagerAdapter {
String image_url;
private Context mContext;
int size;
ArrayList<News> Newslist;
File file,file1;
StringBuffer buffer,buffer1;
DataHandler handler;
public CustomPagerAdapter(Context context, int arraysize, ArrayList<News> newslist) {
mContext = context;
size=arraysize;
Newslist=newslist;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.row, collection, false);
collection.addView(layout);
TextView tvtitle=(TextView)layout.findViewById(R.id.tvtitle);
TextView tvbody=(TextView)layout.findViewById(R.id.tvbody);
ImageView im=(ImageView)layout.findViewById(R.id.NewsImage);
im.setScaleType(ImageView.ScaleType.FIT_XY);
SugarContext.init(mContext);
ConnectivityManager ConnectionManager=(ConnectivityManager)mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=ConnectionManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()==true )
{
tvtitle.setText(Html.fromHtml(Newslist.get(position).getTitle()));
tvbody.setText(Html.fromHtml(Newslist.get(position).getBody()));
image_url = "https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage();
Picasso.with(mContext).load(image_url).into(im);
/*****************88*/
ArrayList<News> content = Newslist;
// String content="hello";
File file,file1;
FileOutputStream outputStream,outputStream1;
try {
//file = File.createTempFile("MyCache", null,getCacheDir());
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");
outputStream = new FileOutputStream(file);
outputStream1 = new FileOutputStream(file1);
outputStream.write(content.get(position).getTitle().getBytes());
outputStream1.write(content.get(position).getBody().getBytes());
//outputStream.write(Integer.parseInt(content.get(position).getImage()));
// outputStream.write(Integer.parseInt(content.get(position).getTitle()));
// outputStream.write(Integer.parseInt(content.get(position).getBody()));
outputStream.close();
Log.d("filecreated", String.valueOf(file));
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader input = null;
BufferedReader input1=null;
file = null;
file1=null;
try {
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");// Pass getFilesDir() and "MyFile" to read file
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
input1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String line,line1;
buffer = new StringBuffer();
buffer1 = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line);
}
while ((line1 = input1.readLine()) != null) {
buffer1.append(line1);
}
String s=buffer.toString();
String t=buffer1.toString();
//Log.d("bufferdsample", buffer.toString());
Toast.makeText(mContext, "asas"+s, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "body"+t, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
/*****************************88*/
/* try {
handler = new DataHandler(mContext);
handler.open();
} catch (Exception e) {
Toast.makeText(mContext, "exc " + e,
Toast.LENGTH_SHORT).show();
}
handler.insertData(Newslist.get(position).getImage(),Newslist.get(position).getTitle(),Newslist.get(position).getBody());
*/
Toast.makeText(mContext, "Network Available", Toast.LENGTH_LONG).show();
}
else
{
BufferedReader input = null;
BufferedReader input1=null;
file = null;
file1=null;
try {
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");// Pass getFilesDir() and "MyFile" to read file
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
input1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String line,line1;
buffer = new StringBuffer();
buffer1 = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line);
}
while ((line1 = input1.readLine()) != null) {
buffer1.append(line1);
}
String s=buffer.toString();
String t=buffer1.toString();
//Log.d("bufferdsample", buffer.toString());
Toast.makeText(mContext, "asas"+s, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "body"+t, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(mContext, "Network Available", Toast.LENGTH_LONG).show();
/* image_url = "https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage();
Picasso.with(mContext).load(image_url).into(im);*/
}
/* String fileName="cachefile";
try {
cacheThis.writeObject(mContext, fileName, Newslist);
} catch (IOException e) {
e.printStackTrace();
}
try {
Newslist.addAll((List<News>) cacheThis.readObject(mContext, fileName));
Log.d("aaasasa", String.valueOf(Newslist));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}*/
// ImageLoader class instance
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
//im.setImageBitmap(getBitmapFromURL("https://3.bp.blogspot.com/-yEE6FqiglKw/VeBH_MmGGzI/AAAAAAAAbHE/HUYcYvkIwl0/s1600/AndroidImageViewSetImageFromURL2.png"));
// im.setImageResource(Uri.parse("https://www.amrita.edu/sites/default/files/%s", Newslist.get(position).getImage()));
// new DownloadImageTask(im).execute("https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage());
return layout;
}
/*public void ofline(View view){
String filr_name="newfile";
FileOutputStream fileOutputStream = mContext.OpenfileOutput(filr_name,MODE_PRIVATE)
}
public void readmessage(View view){
}*/
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return size;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
When device is offline you can import /read from a File or database which contains this json value . After getting internet update the database or file .
For file you must make or move the file in
Environment.getExternalStorageDirectory();
And for writing in a file follow the code
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("test.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
And reading from external storage follow the following code
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("test.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}

Show new id for newly list when it is pressed

I wonder how to show the new list id when it is pressed? Currently the new list is showing the old list id instead itself, but when I close the app and reopen it again, it will display its id.
Firstly the data will retrieved from MySQL and load into android listView. (Assume it has only one list only).
ListView listViewUpdate;
String ID, iD;
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
int mClickedPosition;
String ReceiveProject, ReceiveDescription, ReceiveTimeIn, ReceiveTimeOut;
Integer ReceiveProgress;
String myJSON;
JSONArray details = null;
TextView totalHours;
String MiNtimeIn,MaXtimeOut;
List<DetailsBean> details1=new ArrayList<>();
CustomBaseAdapter objadapter;
public void BuildEditDetails(final String ID) { // Assume the ID is foreign key
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.107.115/Android/CRUD/detailsRetrieve.php?id=" + ID);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
details = jsonObj.getJSONArray(Configs.TAG_RESULTS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String project = c.getString(Configs.TAG_PROJECT);
String description = c.getString(Configs.TAG_WORKDESCRIPTION);
int percentage = c.getInt(Configs.TAG_PERCENTAGE);
String in = c.getString(Configs.TAG_IN);
String out = c.getString(Configs.TAG_OUT);
iD = c.getString(Configs.TAG_ID); // its real id
DetailsBean dbean=new DetailsBean(iD,project,description,percentage,in,out);
details1.add(dbean);
}
objadapter=new CustomBaseAdapter(getActivity(),details1);
listViewUpdate.setAdapter(objadapter);
} catch (JSONException e) {
e.printStackTrace();
}
When pen icon is clicked (mClickedPosition==-1), it will intent to Activity B ,and add a new list in Activity A listView. If list is pressed**(mClickedPosition!==1), it shows its id, and intent to **B for user to edit.
listViewUpdate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
String iD = details1.get(position).getID();
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("iD", iD);
intent.putExtra("ID", ID);
intent.putExtra("mClickedPosition", mClickedPosition);
Toast.makeText(getActivity(), "This is" + iD + ID, Toast.LENGTH_LONG).show();
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
});
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDetails:
mClickedPosition = -1;
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("ID", ID);
// intent.putExtra("iD", iD);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
break;
OnActivityResult Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveProject = data.getStringExtra("project1");
ReceiveDescription = data.getStringExtra("description");
ReceiveProgress = data.getIntExtra("progress", 0);
ReceiveTimeIn = data.getStringExtra("timeIn");
ReceiveTimeOut = data.getStringExtra("timeOut");
if(mClickedPosition==-1)
{ // add list
if(objadapter!=null)
{
objadapter.addNewItem(iD,ReceiveProject,ReceiveDescription,ReceiveProgress,ReceiveTimeIn,ReceiveTimeOut);
}
}
else
{ // update list
if(objadapter!=null)
{
objadapter.changeItem(mClickedPosition,iD,ReceiveProject,ReceiveDescription,ReceiveProgress,ReceiveTimeIn,ReceiveTimeOut);
}
}
}
}
Finally CustomBaseAdapter
public class CustomBaseAdapter extends ArrayAdapter<DetailsBean>{ // for ListView
Activity context;
List<DetailsBean> details;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
super(context, R.layout.retrieve_details, details);
this.context = context;
this.details = details;
}
public void changeItem(int m,String ID,String Project,String Description,int Percentage,String in,String out)
{
DetailsBean obj = new DetailsBean(ID, Project, Description, Percentage, in, out);
obj.setProject(Project);
obj.setProgress(Percentage+"");
obj.setTimeIn(in);
obj.setTimeOut(out);
obj.setDescription( Description);
details.set(m,obj);
this. notifyDataSetChanged();
}
public void addNewItem(String ID,String Project,String Description,int Percentage,String in,String out) {
DetailsBean obj = new DetailsBean(ID, Project, Description, Percentage, in, out);
obj.setProject(Project);
obj.setProgress(Percentage+"");
obj.setTimeIn(in);
obj.setTimeOut(out);
obj.setDescription( Description);
details.add(obj);
this.notifyDataSetChanged();
}
New list already can added below the previous list, but when I click
the new list, it still showing the old list id..How can I make it
display its id? Thanks
When come to this class, it retrieve value from MySQL
When I click 1 list or 2 list, it display their id, (1 and 2)
Now I added a new list , 3 list now
when I click the third list, it suppose to display 3 but it display 2
Show new id for newly list when it is pressed
Use onPostExecute of AddMore class for getting latest id and sending data back to previous Activity.like:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
try{
JSONObject jsonObject=new JSONObject(s);
int latestID=jsonObject.optInt("lastId");
//call setResult here
....
returnIntent.putExtra("project1", project1);
returnIntent.putExtra("description", description);
returnIntent.putExtra("progress", progress);
returnIntent.putExtra("timeIn", timeIn);
returnIntent.putExtra("iD", latestID); //<<<
}catch(Exception ex){
}
}
Try in adapter CustomBaseAdapter class:
public List<DetailsBean> getDetails(){
return details;
}
in onItemClick
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
String iD = listViewUpdate.getDetails().get(position).getID();
//so check id here
....
check onActivityResult:
what is iD ?? What is value of this variable?
objadapter.addNewItem(iD,ReceiveProject,ReceiveDescription,ReceiveProgress,ReceiveTimeIn,ReceiveTimeOut

Can't properly change my LinearLayout to ListView

Here is ,my code for selecting images and texts from mysql database through php.And it is displaying in a linearlayout in a scrollview.All i want to do is change my layout to listview like this example.
I tried listview and other many ways but its not working properly.I'm new in android,so im trying for a long time.Please help me by editing my code for my requirement.Please.
JAVA
#SuppressLint("NewApi")
public class News_and_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;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_and_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.activity_news_and_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
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());
// Toast.makeText(getActivity(),image, Toast.LENGTH_LONG).show();
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(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
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);
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.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
// img.buildDrawingCache();
// final Bitmap bmap = img.getDrawingCache();
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
startActivity(intent);
}
});
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("image", image);
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.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();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("http://www.google.com");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
XML
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"[![enter image description here][1]][1]
(source: codelearn.org)
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
>
<LinearLayout
android:id="#+id/newslayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffffff"
>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
You cannot call display() from within AsyncTask to display results in listview.
You should follow the following steps
Inside on create, Call AsyncTask to fetch the data from server and populate this into an Array List. While async task is running, make sure you display a progress dialogue so that user cannot do anything in the UI thread.
Inside on create, do initialize your listview.
inside on Post execute of AsyncTask, after you have populated all the elements in the arraylist, call the adapter to populate the listview.
Define an adapter which extends BaseAdapter using which you can populate the listview from the array list.
You may want to check out this link for a similar working example.

Downloading images from a link displaying them in a listview

I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html

Android Fragment - SlidingMenu - ListActivity

So I have the slidingmenu(jfeinstein10) library added to my project and the menu working. The problem I have run into is based on my app extends ListActivity.
I have seen a couple questions about this and most suggest extending to Fragment to get Fragments working for the menu. I wanted to know if there was a way to not use Fragments to get the menu list to work.
Every time I move to SlidingFragmentActivity or any other Fragment Activity, onListItemClick and other methods start breaking.
Below is my code:
public class MainListActivity extends ListActivity {
public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
private SlidingMenu menu;
static final String KEY_TITLE = "title";
static final String KEY_AUTHOR = "author";
static final String KEY_IMAGE = "image";
ListView list;
LazyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setBehindContentView(R.layout.menu_frame);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidth(5);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setBehindWidth(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setMenu(R.layout.menu_frame);
//getFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuFragment()).commit();
if(isNetworkAvailable()){
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
mProgressBar.setVisibility(View.VISIBLE);
getBlogPostsTask.execute();
}else{
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
try{
JSONArray jsonPosts = mBlogData.getJSONArray("items");
JSONObject jsonPost = jsonPosts.getJSONObject(position);
String blogSummary = jsonPost.getString("summary");
String blogUrl = jsonPost.getString("bitly");
Intent intent = new Intent(this, BlogWebViewActivity.class);
intent.setData(Uri.parse(blogSummary));
intent.putExtra("mUrl",blogUrl);
startActivity(intent);
}catch(JSONException e){
logException(e);
}
}
private void logException(Exception e) {
Log.e(TAG, "Exception caught!", e);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if(mBlogData == null){
updateDisplayForError();
}else{
try {
JSONArray jsonPosts = mBlogData.getJSONArray("items");
ArrayList<HashMap<String,String>> blogPosts = new ArrayList<HashMap<String,String>>();
for (int i=0;i<jsonPosts.length();i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String tag = post.getString(KEY_AUTHOR);
tag = Html.fromHtml(tag).toString();
String image = post.getString(KEY_IMAGE);
image = Html.fromHtml(image).toString();
HashMap<String, String> blogPost = new HashMap<String,String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_AUTHOR, tag);;
blogPost.put(KEY_IMAGE, image);
blogPosts.add(blogPost);
}
list=getListView();
LazyAdapter adapter = new LazyAdapter(this, blogPosts);
list.setAdapter(adapter);
} catch (JSONException e) {
logException(e);
}
}
}
private void updateDisplayForError() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.error_title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok,null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Object... params) {
int responseCode = -1;
JSONObject jsonResponse = null;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.domain.com/app_json.js");
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
responseCode = statusLine.getStatusCode();
if(responseCode == HttpURLConnection.HTTP_OK){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
builder.append(line);
}
jsonResponse = new JSONObject(builder.toString());
}else{
Log.i(TAG, "HTTP Failed: "+responseCode);
}
} catch (MalformedURLException e) {
logException(e);
} catch (IOException e) {
logException(e);
}
catch(Exception e){
logException(e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result){
mBlogData = result;
handleBlogResponse();
}
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.showContent();
} else {
super.onBackPressed();
}
}
}
I have the menu items stored in /values/array.xml as a string-array.
I have setup a fragment as well, but dont know how to access it without extending to Fragment from ListActivity.
Below is my Fragment based on the example fragments from github:
public class MenuFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.menu_list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] colors = getResources().getStringArray(R.array.menu_items);
ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, colors);
setListAdapter(colorAdapter);
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
switch (position) {
case 0:
//newContent = new ColorFragment(R.color.red);
break;
case 1:
//newContent = new ColorFragment(R.color.green);
break;
case 2:
//newContent = new ColorFragment(R.color.blue);
break;
case 3:
//newContent = new ColorFragment(android.R.color.white);
break;
case 4:
//newContent = new ColorFragment(android.R.color.black);
break;
}
if (newContent != null)
switchFragment(newContent);
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
}
}
Thanks

Categories

Resources