Pick Image from Gallery and Creating a thumbnail in the imageview - android

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.

Related

firebaseRecyclerAdapter gets filled, yet wont show anything in a dialog - Android Studio

So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.

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);
}
}
});
}
}

Android Picasso Fragment Pic from URL

I've got problem to load pic from URL do my fragment by Picasso.
When I start app it's start without any errors but pic is not loading.
My app has one MainActivity and three fragments. Below I paste xml of mainlayout and one fragment class. The best for me is this scenario:
when user click button on fragment three(red on image), pic will load from url to imageView which is located on fragment two (yellow on image) above of fragment three.
Please help
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasadown extends Fragment {
private klasadownlistener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentdown, container, false);
ImageView img = (ImageView) view.findViewById(R.id.imgVV);
Context c = getActivity().getApplicationContext();
Picasso.with(c).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.fit().into(img);
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMenu:
updateText("Menu");
SetImage();
break;
case R.id.btnKontakt:
updateText("Kontakt");
break;
default:
break;
}
}
};
Button btnMenu = (Button) view.findViewById(R.id.btnMenu);
Button btnKontakt = (Button) view.findViewById(R.id.btnKontakt);
btnKontakt.setOnClickListener(clickListener);
btnMenu.setOnClickListener(clickListener);
return view;
}
public interface klasadownlistener {
public void onItemSelected(String txt);
}
private void updateText(String txt) {
listener.onItemSelected(txt);
}
public void SetImage() {
ImageView img = (ImageView) getView().findViewById(R.id.imgVV);
Picasso.with(getActivity().getApplicationContext()).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").into(img);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof klasadownlistener) {
listener = (klasadownlistener) activity;
} else {
throw new ClassCastException(activity.toString() + " musi implementowa� interfejs: OverviewFragment.OverviewFragmentActivityListener");
}
}
}
<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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<fragment
android:id="#+id/fragmentup"
class="testowy.com.testowyfragment2.Klasaup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5">
</fragment>
<fragment
android:id="#+id/fragmentcenter"
class="testowy.com.testowyfragment2.Klasacenter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
<fragment
android:id="#+id/fragmetdown"
class="testowy.com.testowyfragment2.Klasadown"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
</LinearLayout>
package testowy.com.testowyfragment2;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasacenter extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragmentcenter, container, false);
return view;
}
public void SetText(String txt){
TextView view = (TextView) getView().findViewById(R.id.fragmentcenterText);
view.setText(txt);
}
}
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends Activity implements Klasadown.klasadownlistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemSelected(String txt) {
Klasacenter fragment = (Klasacenter) getFragmentManager()
.findFragmentById(R.id.fragmentcenter);
// sprawdzamy czy fragment istnieje w tej aktywno�ci
if (fragment != null && fragment.isInLayout()) {
// ustawiamy teskt we fragmencie
fragment.SetText(txt);
ImageView img = (ImageView) findViewById(R.id.imgV);
Picasso.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").fit().into(img);
}
}
}
It's stupid to say but I forget to add internet permission:)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
now everything is ok!

Saving path of pdf file in internal storage into Sqlite

I am new to android and i am making an application which is take information from visitor's and make a pdf from it and save it internal storage,it also have the option for printing the information via printers connected through wifi
Here is my main java file Visitor_pass -
package com.example.sayedshazeb.practical1;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.nfc.Tag;
import android.print.PrintManager;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.content.Context;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;
import android.graphics.pdf.PdfDocument;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
public class Visitor_pass extends ActionBarActivity implements ImageAndTextContainer {
ImageView iv;
public Context c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visitor_pass);
iv = (ImageView) findViewById(R.id.image);
Button cbtn = (Button)findViewById(R.id.captureimage);
cbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
});
Button pbtn = (Button) findViewById(R.id.print);
pbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
printDocument(v);
}
});
Button s =(Button)findViewById(R.id.Dbsave);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void printDocument(View view)
{
// Get a PrintManager instance
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
// Give the job a name.
String jobName = this.getString(R.string.app_name) +
" Document";
// Start a print job, passing a printDocumentAdapter as
//argument to handle the generation of a print document
MyPrintDocumentAdapter printDoc = new MyPrintDocumentAdapter(this);
printManager.print(jobName, printDoc, null);
}
#Override
public Bitmap getImage() {
ImageView imageView = (ImageView) findViewById(R.id.image);
Bitmap image = null;
// Get the image
if ((imageView.getDrawable()) != null) {
// Send it to the print helper
image = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
}
return image;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public class MyPrintDocumentAdapter extends PrintDocumentAdapter
{
private ImageAndTextContainer imageAndTextContainer;
Context context;
private int pageHeight;
private int pageWidth;
public PdfDocument myPdfDocument;
public int totalpages = 1;
String pts;
String ats;
String cts;
public MyPrintDocumentAdapter(ImageAndTextContainer container) {
this.context =context;
this.imageAndTextContainer = container;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
myPdfDocument = new PrintedPdfDocument(context, newAttributes);
pageHeight =
newAttributes.getMediaSize().getHeightMils()/1000 * 72;
pageWidth =
newAttributes.getMediaSize().getWidthMils()/1000 * 72;
if (cancellationSignal.isCanceled() ) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo
.Builder("print_output.pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
for (int i = 0; i < totalpages; i++) {
if (pageInRange(pages, i))
{
PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder(pageWidth,
pageHeight, i).create();
PdfDocument.Page page =
myPdfDocument.startPage(newPage);
if (cancellationSignal.isCanceled()) {
callback.onWriteCancelled();
myPdfDocument.close();
myPdfDocument = null;
return;
}
drawPage(page, i);
myPdfDocument.finishPage(page);
}
}
try {
myPdfDocument.writeTo(new FileOutputStream(
destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
myPdfDocument.close();
myPdfDocument = null;
}
callback.onWriteFinished(pages);
}
private boolean pageInRange(PageRange[] pageRanges, int page)
{
for (int i = 0; i<pageRanges.length; i++)
{
if ((page >= pageRanges[i].getStart()) &&
(page <= pageRanges[i].getEnd()))
return true;
}
return false;
}
private void drawPage(PdfDocument.Page page,
int pagenumber) {
Canvas canvas = page.getCanvas();
pagenumber++; // Make sure page numbers start at 1
int titleBaseLine = 72;
int leftMargin = 54;
EditText pt = (EditText)findViewById(R.id.textname);
EditText ct = (EditText)findViewById(R.id.textphone);
pts = pt.getText().toString();
EditText at = (EditText)findViewById(R.id.textaddress);
ats = at.getText().toString();
cts = ct.getText().toString();
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
int day = datePicker.getDayOfMonth();
String d = ""+day;
int month = datePicker.getMonth() + 1;
String m = ""+month;
int year = datePicker.getYear();
String y=""+year;
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(40);
canvas.drawText("Visitor Details " + pagenumber, leftMargin, titleBaseLine, paint);
paint.setTextSize(25);
canvas.drawText("Name :", leftMargin, titleBaseLine + 400, paint);
canvas.drawText(pts ,leftMargin + 110,titleBaseLine + 400,paint);
canvas.drawText("Address :",leftMargin,titleBaseLine + 450,paint);
canvas.drawText(ats ,leftMargin + 110,titleBaseLine + 450,paint);
canvas.drawText("Number :",leftMargin,titleBaseLine + 500,paint);
canvas.drawText(cts ,leftMargin + 110,titleBaseLine + 500,paint);
canvas.drawText("Date :" ,leftMargin,titleBaseLine + 550,paint);
canvas.drawText( d + "/" +m+"/"+y ,leftMargin+110,titleBaseLine + 550,paint);
Rect imageRect = new Rect(100, 100, canvas.getWidth() - 240, canvas.getHeight() / 2 - 10);
drawImage(imageAndTextContainer.getImage(), canvas, imageRect);
}
private void drawImage(Bitmap image, Canvas canvas, Rect r) {
canvas.drawBitmap(image, null, r, new Paint());
}
}
}
And Here is my main Xml file-
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Visitor_pass"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Visitor&apos;s Pass"
android:id="#+id/visitorpass"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:textSize="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/textname"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:hint="Enter visitor&apos;s name"
android:focusableInTouchMode="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:ems="10"
android:id="#+id/textaddress"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:hint="Enter Address"
android:focusableInTouchMode="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/textphone"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:focusableInTouchMode="true"
android:hint="Enter Number" />
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/datePicker"
android:layout_gravity="center_horizontal"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
<ImageView
android:layout_width="200dp"
android:layout_height="150dp"
android:id="#+id/image"
android:layout_gravity="center"
android:layout_marginTop="10dp" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Capture Image"
android:id="#+id/captureimage"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Save "
android:id="#+id/Dbsave"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Print"
android:id="#+id/print"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="Discard"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
Here is the print_dialog 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="fill_parent">
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
Now i want to save the path of a pdf file created and saved in internal storage to be saved in my sqlite database. I know how to store values into database i just wanna know how to get the path of a file stored in my internal storage??
"i just wanna know how to get the path of a file stored in my internal storage??"
Have you tried getFilesDir()? Example.
String path = this.getFilesDir().toString()+"/"+nameOfFile;
You can use the Environment.getExternalStorageDirectory()
This method returns the primary external storage directory.
For example, if you have a folder called /pdf, so the path of your file will be:
Environment.getExternalStorageDirectory() + "/pdf/" + <pd_file_name>
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
More info here

My Android ListFragment isn't displaying the list

The following ListFragment doesn't display anything other than a blank screen. I know the data are present. I'm not getting errors, just a blank (white) screen. I'm sure it's something silly. I'm fairly new to Android.
package com.pbs.deliverytrack1;
import com.pbs.deliverytrack1.DBContract;
import com.pbs.deliverytrack1.DBHelper;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OrderListFragment extends ListFragment {
SimpleCursorAdapter mAdapter;
String TAG = "OrderListFragment";
static final String[] PROJECTION = new String[] {
DBContract.DeliveryOrderTable._ID,
DBContract.DeliveryOrderTable.CUSTOMER,
DBContract.DeliveryOrderTable.ADDRESS };
// Selection criteria
static final String SELECTION = "(("
+ DBContract.DeliveryOrderTable.CUSTOMER + " NOTNULL) AND ("
+ DBContract.DeliveryOrderTable.CUSTOMER + " != '' ) AND ("
+ DBContract.DeliveryOrderTable.DELIVERED_DATETIME + " = '' ))";
private OnOrderSelectedListener listener = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String tag = TAG + ".onCreate()";
Log.d(tag,"Fragment created");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String tag = TAG + ".onCreateView()";
Log.d(tag, "Inflating fragment_order_list - or trying to.");
View view = inflater.inflate(R.layout.fragment_order_list, container,
false);
if (view == null) {
Log.d(tag, "Problem inflating view, returned null");
}
initializeList();
return view;
}
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
String tag = TAG + ".onActivityCreated()";
Log.d(tag,"Parent Activity Created");
}
public interface OnOrderSelectedListener {
public void onOrderSelected(long orderId);
// show detail record you dummy
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
String tag = "OrderListFragment.onAttach()";
Log.d(tag,"Attached!");
if (activity instanceof OnOrderSelectedListener) {
listener = (OnOrderSelectedListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
} // onAttach()
public void onStart() {
super.onStart();
Log.d(TAG + ".onStart()", "Started!!!");
}
public void onResume() {
super.onResume();
Log.d(TAG + "onResume()", "Resumed!!!");
}
public void onPause() {
super.onPause();
Log.d(TAG + ".onPause()", "Paused");
}
public void onStop() {
super.onStop();
Log.d(TAG + ".onStop()", "Stopped");
}
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG + ".onDestroyView()", "View Destroyed");
}
public void onDestroy() {
super.onDestroy();
Log.d(TAG + ".onDestroy()", "I'm dying!!!!");
}
public void onDetach() {
super.onDetach();
Log.d(TAG + ".onDetach()", "Off with the fragment!");
}
private void initializeList() {
String tag = TAG + ".initilizeList()";
Log.d(tag,"Setting up cursor.");
// for the cursor adapter, specify which columns go into which views
String[] fromColumns = {
DBContract.DeliveryOrderTable._ID,
DBContract.DeliveryOrderTable.CUSTOMER,
DBContract.DeliveryOrderTable.ADDRESS };
int[] toViews = {
R.id.list_view_order_id,
R.id.list_view_customer_field,
R.id.list_view_address_field };
// create an empty adapter we will use to display the loaded data.
DBHelper dbHelper = new DBHelper(getActivity());
Cursor cursor = dbHelper.getAllOrdersCursor();
if (cursor != null) {
cursor.moveToFirst();
Log.d(tag,"Creating SimpleCursorAdapter mAdapter");
mAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.fragment_order_list_row,
cursor,
fromColumns,
toViews,
0);
setListAdapter(mAdapter);
int count = mAdapter.getCount();
Log.d(tag, "Order Record Count = " + count);
if (mAdapter.isEmpty()) {
Log.d(tag, "Alas! mAdapter is empty");
} // end if mAdapter empty
} else { // cursor is null
Log.d(tag,"The cursor is null");
} // if cursor != null
}
}
This fragment is supposed to show a list derived from a SQLite query. The UI I'm building is a simple split list/detail screen on a tablet. I'm building for pre-Honeycomb, so I'm using the support library.
Let me know if you need to see any other parts of the code.
Here's fragment_order_list.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"
android:orientation="vertical" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#00FF00"
android:drawSelectorOnTop="false" />
<TextView
android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="#string/err_no_data" />
</LinearLayout>
Here's the activity the ListFragment is called from:
package com.pbs.deliverytrack1;
import com.pbs.deliverytrack1.OrderListFragment.OnOrderSelectedListener;
import com.pbs.deliverytrack1.DBHelper;
import com.pbs.deliverytrack1.DeliveryOrder;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainActivity extends FragmentActivity implements
OnOrderSelectedListener {
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String tag = TAG + ".onCreate()";
Log.d(tag, "Setting up database.");
new SetupDatabase().execute(this);
Log.d(tag, "Setting Content View");
setContentView(R.layout.activity_main);
}
#Override
public void onOrderSelected(long orderId) {
String tag = TAG + ".onOrderSelected()";
Log.d(tag,"Creating order detail fragment");
OrderDetailFragment fragment = (OrderDetailFragment) getSupportFragmentManager()
.findFragmentById(R.id.detailFragment);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here's activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="horizontal"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/action_bar_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="com.pbs.deliverytrack1.MyActionBarFragment"
tools:layout="#layout/fragment_actionbar" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal"
>
<fragment
android:id="#+id/listFragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="40"
android:layout_gravity="bottom"
class="com.pbs.deliverytrack1.OrderListFragment" />
<fragment
android:id="#+id/detailFragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="60"
class="com.pbs.deliverytrack1.OrderDetailFragment"
tools:layout="#layout/fragment_order_detail" />
</LinearLayout>
</LinearLayout>
MainActivity's LinearLayout is set to:
android:orientation="horizontal"
But you seem to have a "vertical" design in mind, because your first child's width is "match_parent". This means that the ListView is drawn, just off the right side of the screen... Simply change the root layout's orientation.

Categories

Resources