resolveuri failed on bad bitmap uri when putting on GridView - android

Hello I'm trying to develop android application that pulls all the image from my phone camera and display in GridView. However, I'm getting the following error:
01-11 09:38:38.890: I/System.out(6766): resolveUri failed on bad bitmap uri: /storage/sdcard0/DCIM/.thumbnails/1347279747819.jpg
In fact I'm getting a lot of this, which is why when I test it on my phone, I can see the scroll bar but no thumbnail displayed (except 2 images)
Here's my code that I thought relevant:
package org.dale.dalegetcontent1;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class GetContent1 extends FragmentActivity implements LoaderCallbacks<Cursor>{
/** SimpleCursorAdapter, holds images and layout for the gridview */
SimpleCursorAdapter mAdapter;
#Override
protected void onStart() {
super.onStart();
/** Initializes the Loader */
getSupportLoaderManager().initLoader(0, null, this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_content1);
/** Getting a reference to gridview of the MainActivity layout */
GridView gridView = (GridView) findViewById(R.id.gridview);
/** Create an adapter for the gridview */
/** This adapter defines the data and the layout for the grid view */
mAdapter = new SimpleCursorAdapter(
getBaseContext(),
R.layout.gridview,
null,
new String[] { "_data","_id"} ,
new int[] { R.id.img},
0
);
/** Setting adapter for the gridview */
gridView.setAdapter(mAdapter);
/** Loader to get images from the SD Card */
getSupportLoaderManager().initLoader(0, null, this);
/** Defining item click listener for the grid view */
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
/** Getting the cursor object corresponds to the clicked item */
Cursor c1 = (Cursor ) arg0.getItemAtPosition(position);
/** Getting the image_id from the cursor */
/** image_id of the thumbnail is same as the original image id */
String id = c1.getString(c1.getColumnIndex("image_id"));
/** Creating a bundle object to pass the image_id to the ImageDialog */
Bundle b = new Bundle();
/** Storing image_id in the bundle object */
b.putString("image_id", id);
/** Instantiating ImageDialog, which displays the clicked image */
ImageDialog img = new ImageDialog();
/** Setting the bundle object to the ImageDialog */
img.setArguments(b);
/** Opening ImageDialog */
img.show(getSupportFragmentManager(), "IMAGEDIALOG");
return ;
}
};
/** Setting itemclicklistener for the grid view */
gridView.setOnItemClickListener(itemClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_get_content1, menu);
return true;
}
/** A callback method invoked by the loader when initLoader() is called */
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
/** Getting uri to the Thumbnail images stored in the external storage */
Uri uri = MediaStore.Images.Thumbnails.getContentUri("external");
System.out.println("Thumb URI: "+uri.toString());
/** Invoking the uri */
return new CursorLoader(this, uri, null, null, null, null);
}
/** A callback method, invoked after the requested content provider returned all the data */
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
mAdapter.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
}
And my gridview.xml under layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/img"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/img_description"
android:padding="10dp"
android:adjustViewBounds="true"
/>
</LinearLayout>
And my activity_get_content1.xml under layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GetContent1" >
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
/>
</RelativeLayout>
Thanks, happy to provide more info if required
Cheers, Dale

Maybe you should add this permission in the AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Related

having trouble with TabLayout using fragments and JSON

Hi I been trying for a while to figure this out and checked a lot of post. I am having this problem when I switch to a new tab only the XML layout is showing. Though when I start on the first tab and fragment the json content shows up how I like. I am not sure how to get the json content to change for a new tab.
Fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Random;
/**
* A simple {#link Fragment} subclass.
*/
public class TVFragment extends Fragment {
public TVFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tv_activity, container, false);
ArrayList<String> media = new ArrayList<String>();
media.add("movie1");
media.add("movie2");
media.add("movie3");
this.loadMovieInfo(media);
// loadMoviePoster(media);
return rootView;
}
private void loadMovieInfo(ArrayList<String> media) {
Random random = new Random();
int x = (int) random.nextInt(media.size()) * 1;
//Use Ion to get json info for movie from movie/tv api.
Ion.with(this)
.load("http://www.omdbapi.com/?t=" + media.get(x)
+ "&apikey0000")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
// create json object
JSONObject json = new JSONObject(result);
//get json title and poster from the json object.
String name = json.getString("Title");
String urlString = json.getString("Poster");
//get TextView to display title
TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
mediaName.setText(name);
/* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
*/
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);
} catch (JSONException jsone) {
Log.wtf("Json Import problems", jsone);
}
}
});
}
}
MainActivity
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Samuel on 2/12/2018.
*/
public class TechnologyResultsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the tv_activitylayout file
setContentView(R.layout.tab_viewpager_activity);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
MediaTypeAdapter adapter = new MediaTypeAdapter(getSupportFragmentManager(),getApplicationContext());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
Adapter
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Samuel on 2/14/2018.
*/
public class MediaTypeAdapter extends FragmentPagerAdapter {
public MediaTypeAdapter(FragmentManager fragmentManager, Context applicationContext){
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new TVFragment();
} else if (position == 1) {
return new MovieFragment();
}
else {
return new MovieFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "TV";
} else {
return "MOVIES";
}
}
}
tablayout
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
movie_activity 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="wrap_content"
android:orientation="horizontal"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom"
android:paddingBottom="16dp">
<ImageView
android:id="#+id/poster"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:src="#drawable/poster"
android:layout_weight="1"
/>
<ScrollView
android:id="#+id/synopsis_scroll"
android:layout_width="match_parent"
android:layout_height="81dp"
android:padding="8dp">
<TextView
android:id="#+id/synopsis_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Academy Award nominee, heart-warming, hit comedy from producer Judd Apatow (Bridesmaids and Trainwreck). The Big Sick is based on the real-life courtship between Pakistan-born comedian Kumail Nanjiani (Nanjiani) and grad student Emily Gordon (Zoe Kazan) who fall in love but struggle while dealing with Emily's mysterious illness and their families culture clash. Also staring Ray Romano and Holly Hunter. Included with Prime."/>
</ScrollView>
</LinearLayout>
</LinearLayout>
you have to create a new class moviefragment and have to write code to fetch movies in that.
public class MovieFragment extends Fragment{
TechnologyResultsActivity technology;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
technology= (TechnologyResultsActivity) context;
}
public static Fragment newInstance(Bundle bundle){
MovieFragment movie=new MovieFragment();
if(bundle!=null){
movie.setArguments(bundle);
}
return movie;
}
#Override
public void onResume() {
super.onResume();
// this will only called when fragment is visible to user
if(isVisible()) {
if (Constant.isInternetConnected(homeActivity)) {
ArrayList<String> media = new ArrayList<String>();
media.add("movie1");
media.add("movie2");
media.add("movie3");
loadMovieInfo(media)
} else {
Toast.makeText(homeActivity, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
}
private void loadMovieInfo(ArrayList<String> media) {
Random random = new Random();
int x = (int) random.nextInt(media.size()) * 1;
//Use Ion to get json info for movie from movie/tv api.
Ion.with(this)
.load("http://www.omdbapi.com/?t=" + media.get(x)
+ "&apikey0000")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
// create json object
JSONObject json = new JSONObject(result);
//get json title and poster from the json object.
String name = json.getString("Title");
String urlString = json.getString("Poster");
//get TextView to display title
TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
mediaName.setText(name);
/* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
*/
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);
} catch (JSONException jsone) {
Log.wtf("Json Import problems", jsone);
}
}
});
}
}

Pick Image from Gallery and Creating a thumbnail in the imageview

I am stuck on trying to make the gallery work. Partially because it is a fragment.
What I would like to do in this fragment is to pick up image, make a copy in my app's folder, scale the image to my image-view for thumbnail. Also, use this image in other sections of the app, so save location of image. I am using Realm to save that location.
Thank you for your help
Here is the code:
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.content.Intent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.heinrichreimersoftware.materialintro.slide.FragmentSlide;
import io.realm.Realm;
public class Step3 extends FragmentSlide.FragmentSlideFragment implements View.OnClickListener {
boolean STEP3_PROCEEDABLE = true;
private static final int PICK_IMAGE = 1;
AppCompatImageView imgView;
Button imgButton;
private OnFragmentInteractionListener mListener;
public Step3(){
//Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*/
public static Step3 newInstance() {
Step3 fragment = new Step3();
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.add_routine_slide3, container, false);
imgButton = (Button) rootView.findViewById(R.id.imgButton);
imgView = (AppCompatImageView) rootView.findViewById(R.id.imgView);
imgButton = (Button) inflater.inflate(R.layout.add_routine_slide3, container, false);
imgButton.setOnClickListener(this);
return rootView;
}
public void onButtonPressed() {
if (mListener != null) {
mListener.onFragmentInteraction(STEP3_PROCEEDABLE);
}
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(boolean proceedable);
}
}
And here is the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
android:foregroundGravity="center"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rou_Image"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center"
/>
<TextView
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add a picture to capture your routine."
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="center"
/>
<Button
android:text="Select Image"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:id="#+id/imgButton" />
<AppCompatImageView
android:layout_width="137dp"
android:layout_height="wrap_content"
app:srcCompat="#android:drawable/gallery_thumb"
android:id="#+id/imgView"
android:layout_weight="0.20" />
</LinearLayout>
</LinearLayout>
You can check out Picasso Library for this. You can load image from Storage and show it to ImageView as described by for3st.
File f = new File("path-to-file/file.png")
Picasso.with(getActivity()).load(f).into(imageView);
Additionally you can also use it to scale your image
Picasso.with(getActivity()).load(f).resize(100,100).into(imageView);
And to save the image in your app directory you can use it like this
Bitmap bitmap;
Picasso.with(getActivity()).load(f).resize(100,100).into(imageView, new Callback() {
#Override
public void onSuccess() {
bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
}
#Override
public void onError() {
}
});
File directory = new File(Environment.getExternalStorageDirectory().toString()+"/MyAppFolder");
if(!directory.exists()){
directory.mkdirs();
}
File file = new File(directory,new Random().nextInt(10000)+".png");
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
fos.flush();
fos.close();
}catch (IOException e){e.printStackTrace();}
//Gallery Refresh
MediaScannerConnection.scanFile(getApplicationContext(), new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
Hope this helps.

NULL object occurs when implement listener in ListView by using SimpleCursorAdapter

I'm creating an activity with a list view to show contacts and I'm using a custom adapter which extends SimpleCursorAdapter. The layouts configuration is showed below.
Activity layout file: activity_load_contacts.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/contacts_list_view" >
</ListView>
</LinearLayout>
List item layout file: contacts_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:id="#android:id/text1"
android:minHeight="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceMedium">
</TextView>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="#+id/load_contact_checkbox"
android:clickable="false">
</CheckBox>
</LinearLayout>
Custom adapter class:
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Created by admin on 12/08/2016.
*/
public class LoadContactListAdapter extends SimpleCursorAdapter {
public LoadContactListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public void bindView(View view, Context context, Cursor cur) {
TextView contactName = (TextView)view.findViewById(android.R.id.text1);
CheckBox cbx = (CheckBox)view.findViewById(R.id.load_contact_checkbox);
if(contactName != null) {
contactName.setText(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
}
if(cbx != null) {
cbx.setId(cur.getInt(cur.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
}
The customer adapter class works fine as it can load contacts to list view.
Main activity class:
import android.annotation.SuppressLint;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class LoadContactsActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
/*
* Defines an array that contains column names to move from
* the Cursor to the ListView.
*/
#SuppressLint("InlinedApi")
private final static String[] FROM_COLUMNS = {
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME
};
/*
* Defines an array that contains resource ids for the layout views
* that get the Cursor column contents. The id is pre-defined in
* the Android framework, so it is prefaced with "android.R.id"
*/
private final static int[] TO_IDS = {
android.R.id.text1
};
// Define global mutable variables
// Define a ListView object
ListView mContactsList;
// Define variables for the contact the user selects
// The contact's _ID value
long mContactId;
// The contact's LOOKUP_KEY
String mContactKey;
// A content URI for the selected contact
Uri mContactUri;
// An adapter that binds the result Cursor to the ListView
private LoadContactListAdapter mCursorAdapter;
#SuppressLint("InlinedApi")
private static final String[] PROJECTION =
{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.LOOKUP_KEY,
Build.VERSION.SDK_INT
>= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY :
ContactsContract.Contacts.DISPLAY_NAME
};
// The column index for the _ID column
private static final int CONTACT_ID_INDEX = 0;
// The column index for the LOOKUP_KEY column
private static final int LOOKUP_KEY_INDEX = 1;
// Defines the text expression
#SuppressLint("InlinedApi")
private static final String SELECTION =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?" :
ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?";
// Defines a variable for the search string
public static String mSearchString;
// Defines the array to hold values that replace the ?
private String[] mSelectionArgs = { mSearchString };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_contacts);
// Sets the toolbar as the app bar for the activity
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
// Gets the ListView from the View list of the parent activity
mContactsList =
(ListView) findViewById(R.id.contacts_list_view);
// Gets a CursorAdapter
mCursorAdapter = new LoadContactListAdapter(
this,
R.layout.contacts_list_item,
null,
FROM_COLUMNS, TO_IDS,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
// Initializes the loader
getLoaderManager().initLoader(0, null, this);
// Set the item click listener to be the current fragment.
mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("OnContactItemClick: ", "*");
/*
* You can use mContactUri as the content URI for retrieving
* the details for a contact.
*/
// !!! Here I got a NULL object
CheckBox cbx = (CheckBox)view.findViewById(R.id.load_contact_checkbox);
if(cbx != null)
{
boolean isChecked = cbx.isChecked();
Log.d("Set checkbox", String.valueOf(isChecked));
cbx.setChecked(!isChecked);
}
else
{
Log.d("Error: ", view.getClass().toString());
}
}
});
}
}
In previous code, when I implement the setOnItemClickListener() function, I try to get the view object of Checkbox. However, in this situation it will return a null object. I really don't know why cause the same method works fine in my custom adapter class. Can anyone help me to find what the problem it is?
I am thinking if the view object passed into bindView method and onItemClick method is the same one?
Thanks a lot if anyone can give me some inspiration.

How to implement Android Fragment Transaction .add syntax error

I'm would like to make my Android application use Fragment Transactions, so that I can
switch between various Fragments display their associated lists. My application
worked fine prior to attempting to convert to just Fragment Transactions. In my initial activity_main.xml,
I removed the android:name="com.birdsall.peter.chap.ChapterFragment", it is my understanding you can't use xml defined fragments
with fragment transactions.
1) I can't seem to get the .add() within
getSupportFragmentManager correct with it's parameters, even with code from a working example.
I have also attempted to use the newer version of FragmentTransactions to no avail.
I even took a working example of code using getSupportFragmentManager / FragmentTransactions,
modified to use the names I had, it worked. I then imported that code into my application
and it fails on the .add() syntax. I'm somewhat new to Android development and can't
pinpoint where I'm going wrong.
Here is my main xml layout for the FrameLayout
activity_main.xml
<?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" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="#+id/chapterfragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Removed this from above <fragment> block to enable Fragment Transaction
android:name="com.birdsall.peter.chap.ChapterFragment" -->
</LinearLayout>
Here is the xml layout for the ChapterFragment ListView
chapterfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/chapterlist" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true" />
</RelativeLayout>
Here is the layout for the details of the list
chapter_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical" android:padding="6dip">
<TextView android:id="#+id/chapter1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView android:id="#+id/textViewLiteral" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/chapter1" android:text=" - "
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView android:id="#+id/chaptertitle1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textViewLiteral"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
Here is the MainActivity.java that I have modified. I left the 'setContentView(R.layout.activity_main);' as I thought I needed to create a view (even though it empty) to add the fragment view to.
package com.birdsall.peter.chap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
public class MainActivity extends FragmentActivity implements ChapterFragment.ChapterSelectedListener {
private static final String TAG = "Main_Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Starting ...");
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
ChapterFragment firstFragment = new ChapterFragment();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
**.add**(R.id.fragment_container, firstFragment).commit();
Log.i(TAG, "Ending ...");
}
} ...
Here is my ChapterFragment.java
package com.birdsall.peter.chap;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ChapterFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
ChapterSelectedListener mCallback;
// Container Activity must implement this interface
public interface ChapterSelectedListener {
public void onChapterSelected(String position, int rowId);
}
public SimpleCursorAdapter dataAdapter;
private static final String TAG = "ChapterFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
View listview = inflater.inflate(R.layout.activity_main,null);
ListView mList =(ListView)listview.findViewById(R.id.chapterlist);
// The desired columns to be bound
String[] columns = new String[] {
TDAdb.COL_CHAPTER,
TDAdb.COL_CHAPTERTITLE};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.chapter1,
R.id.chaptertitle1,
};
// create an adapter from the SimpleCursorAdapter
dataAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.chapter_info,
null,
columns,
to,
0);
mList.setAdapter(dataAdapter);
//Ensures a loader is initialized and active.
getLoaderManager().initLoader(0, null, this);
return listview;
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, " onStart");
displayListView();
Log.i(TAG, " end of onStart");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (ChapterSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ChapterSelectedListener");
}
}
#Override
public void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
Log.i(TAG, " onResume");
getLoaderManager().restartLoader(0, null, this);
}
private void displayListView() {
Log.i(TAG, " Starting displayListView");
// The desired columns to be bound
String[] columns = new String[] {
TDAdb.COL_CHAPTER,
TDAdb.COL_CHAPTERTITLE};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.chapter1,
R.id.chaptertitle1,
};
// create an adapter from the SimpleCursorAdapter
dataAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.chapter_info,
null,
columns,
to,
0);
// get reference to the ListView
ListView listView = (ListView) getView().findViewById(R.id.chapterlist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//Ensures a loader is initialized and active.
getLoaderManager().initLoader(0, null, this);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String chaptervalueselected =
cursor.getString(cursor.getColumnIndexOrThrow(TDAdb.COL_CHAPTER));
mCallback.onChapterSelected(chaptervalueselected, position);
Toast.makeText(getActivity(), "Chapter " + chaptervalueselected, Toast.LENGTH_SHORT).show();
// starts a new Intent to update/delete a Chapter
// pass in row Id to create the Content URI for a single row
//Intent chapterEdit = new Intent(getBaseContext(), ChapterEdit.class);
//Bundle bundle = new Bundle();
//bundle.putString("mode", "update");
//bundle.putString("rowId", rowId);
//chapterEdit.putExtras(bundle);
//startActivity(chapterEdit);
}
});
}
// This is called when a new Loader needs to be created.
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.i(TAG, " onCreateLoader");
String[] projection = {
TDAdb.KEY_ROWID,
TDAdb.COL_CHAPTER,
TDAdb.COL_CHAPTERTITLE};
CursorLoader cursorLoader = new CursorLoader(getActivity(),
TDAProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.i(TAG, " ononLoadFinished");
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.i(TAG, " onLoaderReset");
dataAdapter.swapCursor(null);
}
}
If you are already using the add method of FragmentTransaction you must not include the <fragment tag in your layout. What if you just left your main activity XML like this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
In chapterFragment.java change your import
import android.app.Fragment
To
import android.support.v4.app.Fragment

OnListItemClick is not firing

I am trying to set up an OnItemClickListener for a ListView that was created inside of the main activity (extending Activity). The following code is not firing. Why isn't the onItemClick running?
Main.java
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class Main extends Activity {
/** Called when the activity is first created. */
List<Title> titleList;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set list view
setContentView(R.layout.listview);
setTitle("TITLE");
// Create Parser for raw/countries.xml
TitleParser titleParser = new TitleParser();
InputStream inputStream = getResources().openRawResource(R.raw.titles);
// Parse the input stream
titleParser.parse(inputStream);
// Get Titles
titleList = titleParser.getList();
// Create a customized ArrayAdapter
TitleArrayAdapter adapter = new TitleArrayAdapter(
getApplicationContext(), R.layout.title_listitem, titleList);
// Get reference to ListView holder
lv = (ListView) this.findViewById(R.id.titleLV);
// Set the ListView adapter
lv.setAdapter(adapter);
// on list item click
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Title title = (Title) lv.getItemAtPosition(position);
try{
Class<?> challengeClass = Class.forName("com.glvangorp.app.TITLECHALLENGE");
Intent challengeIntent = new Intent(Main.this, challengeClass);
challengeIntent.putExtra("challenge", title.challenge);
challengeIntent.putExtra("title", title.resourceId);
startActivity(challengeIntent);
} catch(ClassNotFoundException e){
Log.d("TAG", e.getMessage());
e.printStackTrace();
}
}
};
lv.setOnItemClickListener(listener);
}
}
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="#+id/titleLV"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
one reason one not calling is the list item has been set to clickable false. or on the list item you have set some click or touch listener with return true ( make it to return false if you have written).
Maybe it is getting called but you are just getting an ClassNotFoundException thus, you don't know if it doing anything in the OnItemClick ... Why don't you put a Log.d("TAG", e.getMessage); inside the
catch clause.

Categories

Resources