How to enable Horizontal scroll in Android? - android

Basically, the code below is what I am using to retrieve images from a remote server. My problem is, whenever I have large images like 700x700, it shrinks the entire image until it only fits the screen. What I really want is whenever I have large image like that, I want it to stay just the way it is and show a vertical and horizontal scrollbar instead. is this possible to accomplish?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/imageView"
android:visibility="gone"
android:layout_width="200dp"
android:layout_height="200dp"/>
</LinearLayout>
Then my main activity ImageDownload.java
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class ImageDownload extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView mainImageView = (ImageView) findViewById(R.id.imageView);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
String imageurl = "http://4.bp.blogspot.com/-xRyw7I08tDM/TgNqD2Ij-3I/AAAAAAAAAOU/FGjboxE-u2U/s1600/cute_cat_cute_1-s357x422-47520.jpg";
ImageDownloadMessageHandler imageDownloadMessageHandler1= new ImageDownloadMessageHandler(progressBar, mainImageView);
ImageDownlaodThread imageDownlaodThread = new ImageDownlaodThread(imageDownloadMessageHandler1,imageurl);
imageDownlaodThread.start();
}
class ImageDownlaodThread extends Thread {
ImageDownloadMessageHandler imageDownloadMessageHandler;
String imageUrl;
public ImageDownlaodThread(ImageDownloadMessageHandler imageDownloadMessageHandler, String imageUrl) {
this.imageDownloadMessageHandler = imageDownloadMessageHandler;
this.imageUrl = imageUrl;
}
#Override
public void run() {
Drawable drawable = LoadImageFromWebOperations(imageUrl);
Message message = imageDownloadMessageHandler.obtainMessage(1, drawable);
imageDownloadMessageHandler.sendMessage(message);
System.out.println("Message sent");
}
}
class ImageDownloadMessageHandler extends Handler {
ProgressBar progressBar;
View imageTextView;
public ImageDownloadMessageHandler(ProgressBar progressBar, View imageTextView) {
this.progressBar = progressBar;
this.imageTextView = imageTextView;
}
#Override
public void handleMessage(Message message) {
progressBar.setVisibility(View.GONE);
imageTextView.setBackgroundDrawable(((Drawable) message.obj));
imageTextView.setVisibility(View.VISIBLE);
}
}
Drawable LoadImageFromWebOperations(String url) {
Drawable d = null;
InputStream is = null;
try {
is = (InputStream) new URL(url).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
}

Try this:
<ScrollView android:id="#+id/scrollView1"
android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:id="#+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<HorizontalScrollView android:id="#+id/horizontalScrollView1"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<LinearLayout android:id="#+id/linearLayout2"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal">
<TextView/>
<ImageView/>
<ProgressBar/>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>
This way you can have both vertical and horizontal scroll.

The layout element ScrollView and HorizontalScrollView has been invented for this purpose.

Related

how to use asset folder to display in gridview in android studio

i making a gridview to open pdf files from asset
i have used download directory to show pdf file but now i want to use asset
And i am changing main activity and pdf activity to fragments
Guys help me with asset folder
sample code
CustomAdaptor.java
package com.tutorials.hp.gridviewpdf;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<PDFDoc> pdfDocs;
public CustomAdapter(Context c, ArrayList<PDFDoc> pdfDocs) {
this.c = c;
this.pdfDocs = pdfDocs;
}
#Override
public int getCount() {
return pdfDocs.size();
}
#Override
public Object getItem(int i) {
return pdfDocs.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view==null)
{
//INFLATE CUSTOM LAYOUT
view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
}
final PDFDoc pdfDoc= (PDFDoc) this.getItem(i);
TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
ImageView img= (ImageView) view.findViewById(R.id.pdfImage);
//BIND DATA
nameTxt.setText(pdfDoc.getName());
img.setImageResource(R.drawable.pdf_icon);
//VIEW ITEM CLICK
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openPDFView(pdfDoc.getPath());
}
});
return view;
}
//OPEN PDF VIEW
private void openPDFView(String path)
{
Intent i=new Intent(c,PDF_Activity.class);
i.putExtra("PATH",path);
c.startActivity(i);
}
}
PDF_Activity.java
i will be using fragment instead activity
package com.tutorials.hp.gridviewpdf;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
//import com.github.barteksc.pdfviewer.ScrollBar;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import java.io.File;
public class PDF_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
//PDFVIEW SHALL DISPLAY OUR PDFS
PDFView pdfView= (PDFView) findViewById(R.id.pdfView);
//SCROLLBAR TO ENABLE SCROLLING
// ScrollBar scrollBar = (ScrollBar) findViewById(R.id.scrollBar);
// pdfView.setScrollBar(scrollBar);
//VERTICAL SCROLLING
// scrollBar.setHorizontal(false);
//SACRIFICE MEMORY FOR QUALITY
//pdfView.useBestQuality(true)
//UNPACK OUR DATA FROM INTENT
Intent i=this.getIntent();
String path=i.getExtras().getString("PATH");
//GET THE PDF FILE
File file=new File(path);
if(file.canRead())
{
//LOAD IT
pdfView.fromFile(file).defaultPage(1).onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
Toast.makeText(PDF_Activity.this, String.valueOf(nbPages), Toast.LENGTH_LONG).show();
}
}).load();
}
}
}
PDFDoc.java
package com.tutorials.hp.gridviewpdf;
import android.net.Uri;
public class PDFDoc {
String name,path;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
MainActivity.java
i will be using fragment instead activity
i need asset folder to show there pdf files
package com.tutorials.hp.gridviewpdf;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.GridView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final GridView gv= (GridView) findViewById(R.id.gv);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gv.setAdapter(new CustomAdapter(MainActivity.this,getPDFs()));
}
});
}
private ArrayList<PDFDoc> getPDFs()
{
ArrayList<PDFDoc> pdfDocs=new ArrayList<>();
//TARGET FOLDER
File downloadsFolder= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
PDFDoc pdfDoc;
if(downloadsFolder.exists())
{
//GET ALL FILES IN DOWNLOAD FOLDER
File[] files=downloadsFolder.listFiles();
//LOOP THRU THOSE FILES GETTING NAME AND URI
for (int i=0;i<files.length;i++)
{
File file=files[i];
if(file.getPath().endsWith("pdf"))
{
pdfDoc=new PDFDoc();
pdfDoc.setName(file.getName());
pdfDoc.setPath(file.getAbsolutePath());
pdfDocs.add(pdfDoc);
}
}
}
return pdfDocs;
}
}
layout
activity_main.xml
i will be using fragment instead activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.tutorials.hp.gridviewpdf.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
activity_pdf.xml
i will be using fragment instead activity
<?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: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="com.tutorials.hp.gridviewpdf.PDF_Activity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/scrollBar"/>
<com.github.barteksc.pdfviewer.ScrollBar
android:id="#+id/scrollBar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tutorials.hp.gridviewpdf.MainActivity"
tools:showIn="#layout/activity_main">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PDF VIEWER" />
<GridView
android:id="#+id/gv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="2" />
</LinearLayout>
</RelativeLayout>
model.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="5dp"
android:layout_height="200dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/pdfImage"
android:src="#drawable/pdf_icon"
android:layout_width="150dp"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameTxt"
android:padding="10dp"
android:textColor="#color/colorAccent"
android:textStyle="bold"
android:layout_alignParentLeft="true"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Include this permission in manifest if you are storing pdf in external storage.
Use Asset folder like this
AssetManager assetManager = getAssets();
File file = new File(getFilesDir(), "xyz.pdf");
in = assetManager.open("xyz.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
You can open it as an input stream like this from a fragment
reader = new BufferedReader(new InputStreamReader(getActivity().getAssets().open(myfile.pdf))
You don't need permisssions as you're accessing your app's internal files but putting pdf into assets can increase the weight of the app , be careful
and then you can save it as string like that
private StringBuilder text = new StringBuilder();
String mLine;
while ((mLine = reader.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}

The PDF renderer class is not rendering a PDF on Android SDK 21

Here's the code I'm using to render a PDF called "answerkey.pdf" that's stored in "Download/Adobe Reader/answerkey.pdf"
package com.practice.pdftest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends Activity {
private ImageView imageView;
private Button next, previous;
private TextView tv;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage++;
render();
}
});
previous = (Button)findViewById(R.id.previous);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
currentPage--;
render();
}
});
// tv = (TextView)findViewById(R.id.testText);
// tv.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
//
// Toast toast = Toast.makeText(getApplicationContext(),Environment.getExternalStorageDirectory().getAbsolutePath(),Toast.LENGTH_LONG);
// toast.show();
}
private void render() {
try {
imageView = (ImageView)findViewById(R.id.imageView);
int REQ_WIDTH = 1;
int REQ_HEIGHT = 1;
REQ_WIDTH = imageView.getWidth();
REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
PdfRenderer pdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0) {
currentPage=0;
}
else if (currentPage > pdfRenderer.getPageCount()) {
currentPage = pdfRenderer.getPageCount()-1;
}
Matrix matrix = imageView.getImageMatrix();
Rect rect = new Rect(0,0,REQ_HEIGHT,REQ_WIDTH);
pdfRenderer.openPage(currentPage).render(bitmap,rect,matrix,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(matrix);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's the layout.xml file I've made -
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context="com.practice.pdftest.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"
android:layout_weight="4"
android:background="#android:color/white"
android:layout_marginBottom="20dp"
/>
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:id="#+id/testText"-->
<!--android:text="Test"-->
<!--/>-->
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="2"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_marginTop="-100dp">
<Button
android:id="#+id/previous"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Previous"
/>
<Button
android:id="#+id/next"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
</LinearLayout>
For some reason, the PDF just isn't being displayed on screen, I keep getting a white, blank background. What am I doing wrong? Is the path incorrect? I have no SD card on my device. Or am I doing something wrong with the bitmap?
Is the path incorrect?
Yes.
I have no SD card on my device
That is fine. That would be removable storage. I am interpreting "Download/Adobe Reader/answerkey.pdf" as referring to something on external storage.
The recommended way to get this location would be to replace:
File file = new File(Environment.getDataDirectory().getPath()+"Adobe Reader/answerkey.pdf");
with:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "Adobe Reader/answerkey.pdf");
Note that your app will need to request the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission, and that will involve runtime permissions on Android 6.0+ (if your targetSdkVersion is 23 or higher).

VideoView Loader Android

I have implemented videoview in one of my fragment. It's working fine but there is one problem I am unable to set a loader or progress bar over the videoview. My progressbar is working for the whole screen but I only want it over the videoview so that user can understand that a video is loading.
Below is my java and xml code.Please help me with the solution.
FragmentTwo.java
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
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.MediaController;
import android.widget.ProgressBar;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
*/
public class FragmentTwo extends Fragment {
public FragmentTwo() {
// Required empty public constructor
}
public static VideoView videoview;
private static ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view= inflater.inflate(R.layout.fragment_two, container, false);
videoview=(VideoView)view.findViewById(R.id.video);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
return view;
}
void storeRecievedUrl(String url){
String VideoURL = url;
System.out.println(VideoURL);
// progressDialog = ProgressDialog.show(getActivity(), "", "Buffering Video...", true);
try {
MediaController mediacontroller = new MediaController(getActivity());
mediacontroller.setAnchorView(videoview);
Uri video = Uri.parse(VideoURL);
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
videoview.start();
progressBar.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
videoview.requestFocus();
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int i, int i1) {
progressBar.setVisibility(View.GONE);
mediaPlayer.start();
}
});
}
});
}
}
fragment_two.xml
<?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">
<VideoView
android:layout_width="match_parent"
android:id="#+id/video"
android:layout_height="wrap_content" >
</VideoView>
<ProgressBar
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:id="#+id/progressBar1"/>
</LinearLayout>
Below is main activity xml on which i am inflating my fragment two.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:id="#+id/top"
android:layout_height="350dp">
</FrameLayout>
<FrameLayout
android:layout_width="340dp"
android:layout_marginTop="20dp"
android:id="#+id/frgten"
android:layout_below="#+id/top"
android:layout_marginLeft="20dp"
android:layout_marginRight="32dp"
android:layout_height="130dp"/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Please use the following xml to replace your fragment_two.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<VideoView
android:id="#+id/video"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</FrameLayout>
Try using RelativeLayout in fragment_two.xml instead of LinearLayout and put your progressbar on top of videoview.

Rest Template PUT method In Android

I'm new to Android and Rest Template.I have developed a android
screen and display JSON data using Rest Template GET method on my
screen.My next step is to update some fields like edit name and add
missing things and save back to the rest Template.
public class MyPreferences extends AppCompatActivity {
TextView tv;
private Listcp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
TextView fname=(TextView)findViewById(R.id.editfname);
TextView mname=(TextView)findViewById(R.id.editmname);
TextView lname=(TextView)findViewById(R.id.editlname);
TextView nname=(TextView)findViewById(R.id.editnname);
TextView dob=(TextView)findViewById(R.id.editdob);
TextView status=(TextView)findViewById(R.id.editstatus);
TextView homeAddress=(TextView)findViewById(R.id.edithomeAddr);
TextView workAddress=(TextView)findViewById(R.id.editworkAddr);
TextView income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
}
}This Screen is for Get Method
This is what I did Up to Now.
This code is for Get method.
It'll display The screen like in image.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"><![CDATA[
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
]]>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"> <TextView
android:layout_width="wrap_content"
android:scrollbars="vertical"
android:layout_height="wrap_content"
android:text="firstName"/>
<EditText
android:id="#+id/editfname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="middleName"/>
<EditText
android:id="#+id/editmname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lastName"/>
<EditText
android:id="#+id/editlname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nickName"/>
<EditText
android:id="#+id/editnname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dob"/>
<EditText
android:id="#+id/editdob"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="status"/>
<EditText
android:id="#+id/editstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="homeAddress"/>
<EditText
android:id="#+id/edithomeAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="workAddress"/>
<EditText
android:id="#+id/editworkAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="income"/>
<EditText
android:id="#+id/editincome"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:scrollbars="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Preferences"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
This is my layout.
Actually what I'm trying to do is Get User Information and Edit Information and save back to the same end point.
When the user select Update button Then it I'll Display the Updated Screen.
Any help Appreciated.
Anyone Provide code for that.
Thankful to them.
package com.nusecond.suredeal.app.suredeal.activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.http.HttpResponseCache;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.nusecond.suredeal.app.R;
import com.nusecond.suredeal.app.suredeal.pojo.Consumer;
import com.nusecond.suredeal.app.suredeal.pojo.ConsumerProfile;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
public class MyPreferences extends AppCompatActivity {
Button button;
TextView tv;
TextView fname,mname,lname,nname,dob,status,homeAddress,workAddress,income;
private String FName,MName,LName,NName,Dob,Status,HomeAddress,WorkAddress,Income;
private List<ConsumerProfile>cp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
addListenerOnButton();
}
private void addListenerOnButton() {
//final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FName=fname.getText().toString();
MName=mname.getText().toString();
LName=lname.getText().toString();
NName=nname.getText().toString();
Dob=dob.getText().toString();
Status=status.getText().toString();
HomeAddress=homeAddress.getText().toString();
WorkAddress=workAddress.getText().toString();
new HttpUpdateTask().execute();
// Toast.makeText(addListenerOnButton(),"UpdatedSuccessfully",Toast.LENGTH_LONG).show();
Intent intent=new Intent(MyPreferences.this,MainActivity.class);
startActivity(intent);
}
});
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
fname=(TextView)findViewById(R.id.editfname);
mname=(TextView)findViewById(R.id.editmname);
lname=(TextView)findViewById(R.id.editlname);
nname=(TextView)findViewById(R.id.editnname);
dob=(TextView)findViewById(R.id.editdob);
status=(TextView)findViewById(R.id.editstatus);
homeAddress=(TextView)findViewById(R.id.edithomeAddr);
workAddress=(TextView)findViewById(R.id.editworkAddr);
income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
//FName=fname.getText().toString();
}
}
private class HttpUpdateTask extends AsyncTask<Void,Void,ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/" + LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile consumerProfile = new ConsumerProfile();
// String m=FName;
consumerProfile.setFirstName(FName);
fname=(TextView)findViewById(R.id.editfname);
Log.d(" llllllllllllll", "doInBackground: " + FName);
consumerProfile.setMiddleName(MName);
consumerProfile.setLastName(LName);
consumerProfile.setNickName(NName);
consumerProfile.setDob(Dob);
consumerProfile.setStatus(Status);
consumerProfile.setHomeAddress(HomeAddress);
consumerProfile.setWorkAddress(WorkAddress);
consumerProfile.setDob(Income);
restTemplate.put(url,consumerProfile);
Log.d("ettttttttttttttt", "doInBackground: ");
return consumerProfile;
}catch (Exception e){
Log.e( "consumer", e.getMessage(),e);
}
return null;
}
}
}

GridView and ListView in a single fragment

I am doing Android Application for shopping. I need to display products as grid as well as list like this:
https://lh6.ggpht.com/Ly21pAbBRIxAzHn2R119a37NexxtjG5RkQJV8vv0IoCywzksIhKNSCkzWikbUnH8bGY=h900-rw
I don't know how to do this using image button or tabs. Can I change layout of the fragment at runtime? Or I have use 2 different fragments? Please help me.
You have multiple options:
Use RecyclerView
Have two different fragments
Have two different layouts
Use a Framelayout and switch visibility of sub views
Use a ViewFlipper or ViewSwitcher
Why use two layouts when you can simply use RecyclerView and use an imagebutton to handle the clicks and when clicked you can use something like this
// The number of Columns
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
and when the listbutton is clicked you can use something like this:
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
I'm not sure whether it would work or not, its just an example,If you want to learn more about implementing girds and lists using RecyclerView and CardView, check out these tutorials I made:
Custom Android lists with CardView and RecyclerView
Custom Android Grids with Images and Texts using RecyclerView
Just look at this:
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/tlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ListView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
<LinearLayout
android:id="#+id/tgrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" >
<TextView
android:id="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GridView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.1" >
<LinearLayout
android:id="#+id/gridid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:visibility="gone" >
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="5dp" >
</GridView>
</LinearLayout>
<LinearLayout
android:id="#+id/listid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="10sp" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.Adapter.FriendAdapter;
import com.example.bean.FriendBean;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ListView mlist;
private GridView mgrid;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
private FriendAdapter friendAdapter1, friendAdapter2;
private int slist = R.layout.list;
private int sgrid = R.layout.grid;
private TextView list, grid;
LinearLayout listid, gridid, tlist, tgrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlist = (ListView) findViewById(R.id.listView1);
mgrid = (GridView) findViewById(R.id.gridView1);
list = (TextView) findViewById(R.id.textview1);
grid = (TextView) findViewById(R.id.textview2);
listid = (LinearLayout) findViewById(R.id.listid);
gridid = (LinearLayout) findViewById(R.id.gridid);
tlist = (LinearLayout) findViewById(R.id.tlist);
tgrid = (LinearLayout) findViewById(R.id.tgrid);
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"listgrid.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("lg");
Log.e("Length", "" + jsonarray.length());
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
String num = jsonObj.getString("number");
String url = jsonObj.getString("image_url");
FriendBean bean = new FriendBean(url, num);
arr.add(bean);
Log.e("image_url", url);
Log.e("number", num);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tlist.setBackgroundColor(Color.RED);
tgrid.setBackgroundColor(Color.BLACK);
friendAdapter1 = new FriendAdapter(MainActivity.this, slist, arr);
mlist.setAdapter(friendAdapter1);
/*****JUST LOOK AT THIS****/
list.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gridid.setVisibility(View.GONE);
listid.setVisibility(View.VISIBLE);
tlist.setBackgroundColor(Color.RED);
tgrid.setBackgroundColor(Color.BLACK);
friendAdapter1 = new FriendAdapter(MainActivity.this, slist, arr);
mlist.setAdapter(friendAdapter1);
}
});
/*****JUST LOOK AT THIS****/
grid.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gridid.setVisibility(View.VISIBLE);
listid.setVisibility(View.GONE);
tgrid.setBackgroundColor(Color.RED);
tlist.setBackgroundColor(Color.BLACK);
friendAdapter2 = new FriendAdapter(MainActivity.this, sgrid, arr);
mgrid.setAdapter(friendAdapter2);
}
});
}
}

Categories

Resources