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
}
Related
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).
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;
}
}
}
I have used the following code to create a swipe view. This is my java code
package com.lorentzos.swipecards;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class MyActivity extends Activity {
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
FrameLayout.LayoutParams params;
View v;
#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
/*frameLayout=(FrameLayout)v.findViewById(R.id.frame_layout);*/
v=findViewById(R.id.frame_layout);
ButterKnife.inject(this);
/*al.add("c");
al.add("python");
al.add("java");
al.add("html");
al.add("c++");
al.add("css");
al.add("javascript");*/
int height=500;
int width=500;
params = new FrameLayout.LayoutParams(width, height);
/*params.gravity= Gravity.CENTER;*/
al = new ArrayList<>();
for(int i=0; i<=7; i++) {
al.add("php");
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al);
flingContainer.setMaxVisible(4);
/*v.setLayoutParams(params);*/
flingContainer.setAdapter(arrayAdapter);
height=height-20;
}
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(MyActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(MyActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
/*al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;*/
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(MyActivity.this, "Clicked!");
}
});
}
static void makeToast(Context ctx, String s){
Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
}
Below are the xml files
activity_my.xml
<merge
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"
>
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:id="#+id/frame"
android:background="#ffeee9e2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rotation_degrees="15.5"
app:min_adapter_stack="6"
tools:context=".MyActivity" />
<include layout="#layout/buttons" />
</merge>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp">
<TextView
android:id="#+id/helloText"
android:textSize="40sp"
android:textColor="#android:color/white"
android:background="#A5F"
android:gravity="center"
tools:text="#string/hello_world"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="#+id/item_swipe_left_indicator"
android:alpha="0"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_margin="10dp"
android:background="#A5F" />
<View
android:id="#+id/item_swipe_right_indicator"
android:alpha="0"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_margin="10dp"
android:layout_gravity="right"
android:background="#5AF" />
</FrameLayout>
buttons.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/left"
android:layout_margin="10dp"
android:text="Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/right"
android:layout_margin="10dp"
android:text="Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Refer the attached screenshots.
[![enter image description here][2]][2]
But i want the images to come like a stack.. Not exactly overlapped. Refer this
Can anyone help me achieve this?
This is a link with your solution https://github.com/Diolor/Swipecards
Incase you use custom ArrayAdaper on inflating layout this is the code that worked for me
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.swipe_item, parent, false);
I am learning android application development online I have created a project using guideline from http://www.edumobile.org/android/android-beginner-tutorials/ftp-message-viewer-in-android/ but getting error call "ftp_host cannot be resolved or not a field" and "ftp_message_result cannot be resolved or not a field".
My Layout file includes following
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="#string/ftp_server_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="#+id/ftp_host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
<Button android:text="#string/ftp_button_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="showMessage"/>
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/ftp_message_result"
android:textSize="#dimen/ftp_message_size"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
and my MainActivity file looks like below
import java.io.BufferedReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText mFtpHost;
private TextView mFtpMessageResult;
private static final int FTP_PORT = 8080;
/** Initializes the app when it is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mFtpHost = (EditText)findViewById(R.id.ftp_host);
mFtpMessageResult = (TextView)findViewById(R.id.ftp_message_result);
}
public void showMessage(View clickedButton) {
String host = mFtpHost.getText().toString();
try {
Socket socket = new Socket();//(host, FTP_PORT);
BufferedReader in = SocketUtils.getReader(socket);
List<String> results = new ArrayList<String>();
String line = in.readLine();
results.add(line);
if (line.startsWith("220-")) {
while((line = in.readLine()) != null) {
results.add(line);
if ((line.equals("220") || line.startsWith("220 "))) {
break;
}
}
}
String output = makeOutputString(results);
mFtpMessageResult.setText(output);
socket.close();
} catch (Exception e) {
mFtpMessageResult.setText("Unknown host: " + host);
e.printStackTrace(); // View this in DDMS window
}
}
private String makeOutputString(List<String> results) {
StringBuilder output = new StringBuilder();
for (String s: results) {
output.append(s + "\n");
}
return(output.toString());
}
}
Proof if your layout file is really called activity_list_item. If it isn't you have to change
setContentView(R.layout.activity_list_item);
,in your onCreate()-Method, to:
setContentView(R.layout.'THE NAME OF THE LAYOUT');
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.