I want to put extra data to an Intent Camera, that seems simple...
It WAS working some days ago, but I made a lot of changes on code, avd and target version and now it is not working.
The project is now on target version 11.
In fact my goal is to pass an id from my database to construct image name but here a simple code to illustrate my issue.
Here's the sample code:
<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=".CameraTestActivity" >
<Button
android:id="#+id/buttonpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp"
android:text="Button" />
</RelativeLayout>
-
public class CameraTestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_test);
Button buttonpic = (Button)findViewById(R.id.buttonpic);
buttonpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
///first try to put extra data
cameraIntent.putExtra("thisone", "ArgumentFrom");
///second try to put extra data
Bundle extras = new Bundle();
extras.putBoolean("thisalso",true);
cameraIntent.putExtras(extras);
///start camera activty with ID
startActivityForResult(cameraIntent, 1888);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
///if pic is picked and Intent ID is Camera one i.e. 1888
if (requestCode == 1888 && resultCode == RESULT_OK) {
///first try >> Not working
Bundle extra = getIntent().getExtras();////
if (extra != null) {
Log.d("extra: ","isnotnull");
Boolean inputThatIwant = extra.containsKey("thisone");
Boolean inputThatIwantBool = extra.containsKey("thisalso");
Log.d("thisone",inputThatIwant.toString());
Log.d("thisalso",inputThatIwantBool.toString());
}
///Second try >> Some Data is back (pic data... ?)
Bundle extras = data.getExtras();
if (extras != null) {
Log.d("extras: ","isnotnull"); /////-->>Print "isnotnull"
Boolean inputThatIwant = extras.containsKey("thisone");
Boolean inputThatIwantBool = extras.containsKey("thisalso");
Log.d("thisone",inputThatIwant.toString()); /////-->>Print "false"
Log.d("thisalso",inputThatIwantBool.toString()); /////-->>Print "false"
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.camera_test, menu);
return true;
}
}
[EDIT]
Here how I deal with this finally, it can help someone perhaps...
I just "share" within the same class my ID:
private String inputid;
When it's called by Camera request I fill the id in the inputid String and obviously on OnresultActivity this String could not be null, so it works as simple as that...
But if someone has a better solution I'll take it!
Regards....
I don't if its a good prog idea but i created the Uri which i was passing in the intent as a private static member for this class and created a public static function to return this Uri and since in my case I was getting back the result in one of the fragment class of this class , in its(fragment's class) onActivityResult instead of using the the Intent Data parameter which was null(as i found) i used that Uri directly by calling the function(that i created to return Uri). And.... it worked :)
Related
It's been days of researching and I cannot figure out a way to do it.
Here is the link of the library on Github. Library
public class PDFViewActivity1 extends AppCompatActivity {
LinearLayout root;
EditText etPdfUrl;
Button btnDownload;
PDFPagerAdapter adapter;
String id;
ArrayList<String> topicLink;
File file;
String filePath;
PDFViewPager pdfViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_p_d_f_view);
root = (LinearLayout) findViewById(R.id.remote_pdf_root);
final Context ctx = this;
Intent intent = getIntent();
String str = intent.getStringExtra("filePath");
str = str; // This contains the path of the PDF on my device
Log.i("filePathInString", str);
pdfViewPager = new PDFViewPager(ctx, str);
pdfViewPager.setId(R.id.pdfViewPager);
pdfViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
adapter = new PDFPagerAdapter(ctx, str);
pdfViewPager.setAdapter(adapter);
root.removeAllViewsInLayout();
root.addView(pdfViewPager,
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
#Override
protected void onDestroy() {
super.onDestroy();
((PDFPagerAdapter) pdfViewPager.getAdapter()).close();
}
}
The PDF renders perfectly form my device but I cannot see the page numbers, title , total pages of the PDF when the PDF is loaded.
This is my XML file
<?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:id="#+id/remote_pdf_root"
android:orientation="vertical"
android:background="#FFFFFF"
tools:context=".PDFViewActivity1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<es.voghdev.pdfviewpager.library.PDFViewPager
android:id="#+id/pdfViewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
What do I do when the page is scrolled, I cannot figure out a thing , I tried a lot of methods of the PDFAdapter but I an unsuccessful :( How can I do the task ?
RelativeLayout remotePdfRoot = findViewById(R.id.remote_pdf_root);
remotePDFViewPager = new RemotePDFViewPager(this, downloadFileUrlConnection, url, listener);
remotePDFViewPager.setId(R.id.pdfViewPager);
//after file loading success
PDFPagerAdapter adapter = new PDFPagerAdapter(this, FileUtil.extractFileNameFromURL(url));
remotePDFViewPager.setAdapter(adapter);
updateLayout();
private void updateLayout() {
remotePdfRoot.removeAllViewsInLayout();
remotePdfRoot.addView(remotePDFViewPager, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
}
I preview pdf this way and there will be a pagenumber.
You can use https://github.com/barteksc/AndroidPdfViewer library for this and you can get the page count by
`vpPdf.fromAsset("sample.pdf").onError {
Log.i(TAG, "${it.localizedMessage}")
it.printStackTrace()
}.onPageError { _, t ->
t.printStackTrace()
}.enableSwipe(true).swipeHorizontal(true).onPageChange { page, pageCount ->
//here page count is count of page user currently is viewing.
}.load()`
I had to use this lib at work and it is working perfectly fine!!
The above code is from kotlin but you can convert it to java i guess,If you are not able to convert it the kindly comment so i will help you with that too!!.
I am creating a flash card app in android.
For some reason when you hit the button for next card it will randomly show either the next card or a blank card. Sometimes it will be a whole heap of blank cards then one with information. Please find the code below. I am new to creating apps but have done java in the past, it works perfectly in netbeans but not when you run the app.
I want the cards to only appear once thats what the num arraylist is for, it holds the index numbers for the names arraylist. so it appears once but will show blank cards when it shouldnt be. eg: card with info, card without info, card with info. sometimes it will show multiple empty cards then one with info, that is my problem.
I know i havent commented the code,
The first activity:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Character.createArrays();
}
/**
* Called when the user taps the Start button
*/
public void sendMessage(View view) {
Character.getCharName();
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
}
}
The second activity where the cards are called:
public class DisplayMessageActivity extends AppCompatActivity {
public static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
;
}
public void refresh(View view) {
Character.getCharName();
overridePendingTransition(0, 0);
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
this.finish();
overridePendingTransition(0, 0);
}
The methods to get the cards, There are arraylists and the arrays are created correctly and the string arrays are inputted correctly. the CharacterNames array is just an array with names in them. the num array just has index numbers inputted and checked:
public void getCharName() {
RandomNumGen();
mMessage = "";
message = "";
while (num.contains(mRandom)) {
RandomNumGen();
}
for (int i = 0; i < CharacterNames.size(); i++) {
if (i == mRandom) {
mMessage = CharacterNames.get(i);
if (i == mRandom && CharacterNames.contains(mMessage)) {
num.add(mRandom);
card();
}
}
}
}
public void RandomNumGen() {
mRandom = (int) (Math.random() * CharacterNames.size());
}
public String card() {
String[] array;
for (int y = 0; y < names.size(); y++) {
if (Arrays.asList(names.get(y)).contains(mMessage)) {
array = (names.get(y));
for (String array1 : array) {
if (array1 != null && array1.length() > 0) {
message += "\n" + "\n" + (array1);
}
}
Arrays.fill(array, null);
}
}
return message;
}
I hope thats enough information to help.
Thank you so much for understanding an helping me
activity display message 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">
<TextView
android:id="#+id/textView"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="#string/textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:onClick="refresh"
android:text="#string/next_char"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Next character" />
</android.support.constraint.ConstraintLayout>
enter code here
I'm using Android Studio and trying to show some chosen Street View paths in VR. I already have Street View running well and now I'm trying to show it in VR.
I have put the com.google.vr.sdk.widgets.pano.VrPanoramaView in the layout and, inside onCreate in my class, referenced it to a VrPanoramaView variable through findViewById. Now I'm trying to show an image calling a method which I've defined in this class, loadPanoImage. This method loads an image from the storage and shows it through loadImageFromBitmap.
The problem is that it isn't able to show anything, even though I've followed a guide and I've done everything as showed. I've even tryed calling it in different parts of the code (before doing any other action, on clicking a button, before and after showing streetview) but I can't understand why it isn't working and how will I be able to use it to show images taken from StreetView (I don't know if I will be able to do it dinamically or I should download them and put them in the storage).
I'm putting part of the code for reference:
public class VrExperience extends FragmentActivity {
Button buttonCitta;
Button buttonMare;
Button buttonMontagna;
TextView titleTextView;
// George St, Sydney
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
// LatLng with no panorama
private static final LatLng INVALID = new LatLng(-45.125783, 151.276417);
//VrPanoramaView is inserted in the layout
private VrPanoramaView panoWidgetView;
//StreetViewPanorama is another class in my project which shows Street View
private StreetViewPanorama mStreetViewPanorama;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vrexperiences);
panoWidgetView = (VrPanoramaView) findViewById(R.id.pano_view);
panoWidgetView.setEventListener(new VrPanoramaEventListener());
//download image and show it, but it doesn't show anything
loadPanoImage();
titleTextView = (TextView) findViewById(R.id.titleTextView);
buttonCitta = (Button) findViewById(R.id.buttonCitta);
buttonCitta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkReady()) {
return;
}
titleTextView.setVisibility(View.GONE);
buttonCitta.setVisibility(View.GONE);
buttonMare.setVisibility(View.GONE);
buttonMontagna.setVisibility(View.GONE);
loadPanoImage(); //it doesn't show anything
mStreetViewPanorama.setPosition(SYDNEY);
loadPanoImage(); //it doesn't show anything
}
}};
//code for buttonMontagna and buttonMare as well, it's identical
SupportStreetViewPanoramaFragment streetViewPanoramaFragment =
(SupportStreetViewPanoramaFragment)
getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
streetViewPanoramaFragment.getStreetViewPanoramaAsync(
new OnStreetViewPanoramaReadyCallback() {
#Override
public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
mStreetViewPanorama = panorama;
// Only set the panorama to INVALID on startup (when no panoramas have been
// loaded which is when the savedInstanceState is null).
if (savedInstanceState == null) {
mStreetViewPanorama.setPosition(INVALID);
}
}
});
}
/**
* When the panorama is not ready the PanoramaView cannot be used. This should be called on
* all entry points that call methods on the Panorama API.
*/
private boolean checkReady() {
if (mStreetViewPanorama == null)
return false;
return true;
}
/**
* Called when the Animate To Invalid button is clicked.
*/
public void onGoToInvalid(View view) {
if (!checkReady()) {
return;
}
mStreetViewPanorama.setPosition(INVALID);
}
//retrieves image from the assets folder and loads it into the VrPanoramaView
private void loadPanoImage() {
VrPanoramaView.Options options = new VrPanoramaView.Options();
InputStream inputStream = null;
AssetManager assetManager = getAssets();
try {
inputStream = assetManager.open("demo2.jpg");
options.inputType = VrPanoramaView.Options.TYPE_MONO;
panoWidgetView.loadImageFromBitmap(
BitmapFactory.decodeStream(inputStream), options
);
inputStream.close();
} catch (IOException e) {
Log.e("Fail", "Exception in loadPanoImage" + e.getMessage());
}
}
#Override
protected void onPause() {
panoWidgetView.pauseRendering();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
panoWidgetView.resumeRendering();
}
#Override
protected void onDestroy() {
panoWidgetView.shutdown();
super.onDestroy();
}
}
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vrExperienceActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.vr.sdk.widgets.pano.VrPanoramaView
android:id="#+id/pano_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_weight="5"
android:scrollbars="none" />
<TextView
android:id="#+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:text="VR Experience"
android:textAlignment="center"
android:textAppearance="#android:style/TextAppearance.Large"
android:textColor="#0000F0"
android:visibility="visible" />
<Button
android:id="#+id/buttonCitta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Città" />
<fragment
class="com.google.android.gms.maps.SupportStreetViewPanoramaFragment"
android:id="#+id/streetviewpanorama"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
EDIT: #LucioB
a) those are the places I've tried to call loadPanoImage, but neither of them showed anything. It acts as nothing happens calling that method, the program keeps going to the other tasks. I'd like for images to be shown directly in VR when a button is clicked, or if that isn't possible to add the classic cardboard button in Street View mode to pass to VR view.
b) I mean the code isn't doing what I expected it to do. I thought that once I created VrPanoramaView in the layout and used it to show an image through .loadImageFromBitmap it would have shown the image I loaded from asset (I have an image saved on the virtual SD), and that once I was able to do that for a single image I would have found a way to do it for a whole path.
The code doesn't give any exception, I think I'm making a logic mistake or I didn't understand how VR api work.
EDIT: I've found that the java code is working, the problem was in the layout which didn't permit to see VrPanoramaView because it was obscured by StreetViewPanorama
I know that there are a lot of answers to this question already, but I'm still having trouble dealing with this concept.
An answer found here shows:
If you didn't want to use a global variable you could always create a method in your activity to return your string.
public String getMyString(){
return item; }
Then in your current activity you could call:
String myValue = LoginScreen.getMyString();
When I try this method, I am returned an error saying "Non-Static method can not be referenced from a static context". However if I make the method static it says that my variable needs to be static, but I need to update the variable. I'll include my code below.
First Activity -
btnSEARCH.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (editTextSearch.getText().toString() != null) {
SearchQueryTerm = editTextSearch.getText().toString();
editTextSearch.setText("");
}
}
});
public String getMyString(){
return SearchQueryTerm;
}
Second Activity-
String SearchQueryTerm = MainActivity.getMyString();
I truly appreciate any help you can give me in this. Thanks so much!! <3
This is my updated code - however it still crashes :(
Activity 1
public void sendMessageIntent(View view) {
Intent search_intent = new Intent(this, SearchActivity.class);
api_intent.putExtra("my_variable", SearchQueryTerm);
startActivity(search_intent);
}
xml file
<Button
android:id="#+id/button_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="View"
android:onClick="sendMessageIntent"
/>
Activity 2 -
public String SearchQueryTerm
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_variable);
if (extras != null) {
SearchQueryTerm = extras.getString("my_variable");
}
}
Use putExtra method of an object Intent.
In your first activity create for example :
String value = "value";
Intent i = new Intent(getApplicationContext(), MyActivity.class);
i.putExtra("my_variable",value);
startActivity(i);
In your second activity you can retrieve your variable :
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("my_variable");
}
It's the best method to pass a variable between activities.
To show you how it works, i have done this code :
XML of first activity :
<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: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=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editTextSearch"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonSearch"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>
</RelativeLayout>
First Activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSEARCH = (Button) findViewById(R.id.buttonSearch);
btnSEARCH.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editTextSearch = (EditText) findViewById(R.id.editTextSearch);
if (editTextSearch.getText().toString() != null) {
String value = "value";
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("SearchQueryTerm",editTextSearch.getText().toString());
startActivity(i);
editTextSearch.setText("");
}
}
});
}
}
In this first activity we pass the value of the editText in the putExtra method with the key = "SearchQueryTerm".
To retrieve the value of editText do this in your second Activity :
public class Main2Activity extends AppCompatActivity {
String SearchQueryTerm = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
SearchQueryTerm = extras.getString("SearchQueryTerm");
}
System.out.println(SearchQueryTerm);
}
}
Now you have the value of your editText in the variable SearchQueryTerm ( Second Activity ).
It works for me, so there is no reason it dont work for you.
Hope it helps.
a good solution is to add a "model" singleton class, where you store data that have to be shared between your activities
example :
public class Model {
private static Model __instance == null;
private Model() {
}
public static Model instance() {
if (__instance == null) {
__instance = new Model();
}
return __instance;
}
private Object mydataToShare = null;
public void setMyDataToShare(Object mydataToShare) {
this.mydataToShare = mydataToShare;
}
public Object getMyDataToShare() {
return mydataToShare;
}
}
to store data :
Model.instance().setMyDataToShare(<value to store>);
to retrieve data :
Object valueToRetrieve = Model.instance().getMyDataToShare();
it allow you to transfer complex data and separate completely logic part from UI
I am receiving bytes of data like
JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nNVZyY7jNhC991foHCBOVXERBQQBJFu+D9BAfiALkEOAzGV+f15Ra2shqaQz6IFhWzJp8tX+WKIbV19e/qmo+pFw6VnwWTf6+fn36tcfqr/joL4+//nSvb44fwtVze7mq9ffqp+eXDFVr3/8TDy+hAxZcuSpxl3AXYOrFvcdrpju+H7gyuG7pydmeHL4I7OwwZdlvdHRhv0vr3+99K8vnw5BkL3JCYjpdSfPgMGBG2zm5uVbAGhx4fHucH/H+5HazEMlTdlmQG655ycTWdGBTli1AdXgApqYJZ7gbH8Xs/mfHSCKaqUVj18zuvGBb+4S3BA3rqORsOU5NBjTMa/n446SYGoqNZSEuH0nDZaGgegprW4hHcb9BGMGd5fBjIPnXNOQC/i8oKG30OgOGMvdBGg9xy+zyOssmDU5zho0Ngna1qVmlQ7msTMwEpgp6qoWw608YMhRmwIDcwcgfQyVa1o0HpmiLAZr3gf/DE8hDNuNEHrpkxuLLTWf5pLFdyAb5Fz50Grr5IYkOUnlqZZNLeIautUZ1NNrcLqV9xtYCKrrY9JSCZroeNFeuHvgOzMb0cuH8SSYC3uzSYKvm5stA7/Kt/dSUYAtqBMeh7yGeBKcz3nDBK2VbgfwLi3KFsIXvwd5cFBjQh8AltwUn6XmnHwkINQ6OGQnD9XKNQ1t/50EZ93NXAMXDdBCEWOl3moluZ0p9I2YA5+DIZILMpfiP43wC6o1m1WmmCDWYiy9MVgDCXqMJGjKWCiHYlaN/5Re556JZMOZTCkl2KbZ0Y67AoOYJqZpJHLjYvLuBqgH4xSr+izMfob+glI6ior7UaAktLrOVvW3MZewkqb7spiz3mWJ2BX30CKhxU+reBcrsxk4j8RAiGOaaHfzVo6hm8xkrcQZOJxJkhTd2V31/yjOYE2pM5TGP7hz
this bytes are related to pdf.
and String cannot able to store this much of data. So I am using stringbuffer to store this. But stringbuffer also cannot able to store. so how to store this received data.
how to convert this bytes and show in web view.
Update:
I am using the following code.
byte[] decodedString = Base64.decode(ByteCode.toString());
wv.loadData(decodedString.toString(), "application/pdf", "utf-8");
where ByteCode is a type StringBuffer holding the response bytecode from service.
It is not possible to preview pdf document in Android webview. It requires third-party library.
build.Gradle
compile 'com.github.barteksc:android-pdf-viewer:2.7.0'
dialog_pdf_viewer
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2017.
~ Samet Öztoprak
~ All rights reserved.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/dialog_pdf_viewer_close"
style="#style/ExitButtonImageViewStyle"
android:src="#drawable/popup_exit" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:orientation="vertical">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<View style="#style/HorizontalLine" />
<com.pozitron.commons.customviews.ButtonFont
android:id="#+id/dialog_pdf_viewer_button"
style="#style/ButtonPrimary2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="#string/agreed" />
</LinearLayout>
DailogPDFViewer.java
public class DialogPdfViewer extends Dialog {
PDFView pdfView;
byte[] decodedString;
public interface OnDialogPdfViewerListener {
void onAgreeClick(DialogPdfViewer dialogFullEula);
void onCloseClick(DialogPdfViewer dialogFullEula);
}
public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
super(context);
setContentView(R.layout.dialog_pdf_viewer);
findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
}
});
findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
}
});
decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);
pdfView = ((PDFView) findViewById(R.id.pdfView));
pdfView.fromBytes(decodedString).load();
setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
}
return true;
}
});
}
}
From your comments, it appears that your data is not too long for a string, merely too long for logging to display the string. (Logging has a limit of around 4000 characters).
You seem to be working along the right lines
you read the data in to a string
you then base64 decode that data
However, trying to just load that data into a web view is not supported on most (if not all) versions of Android.
I suggest that instead you
write the data out to a file
issue an Intent specifying a FileProvider content URI so that the user's preferred PDF viewer will be used to view the file.
The WebView does not contain a PDF plugin that allow you to display a PDF document.
One solution is to use an Intent object to launch a third-party app
(such as Adobe Acrobat) which can handle the PDF document. However,
this will transfer control over to the third-party app.
If you insists on displaying the PDF document within your own
activity using a WebView, you can use the following trick. You can
use Google Docs to open your PDF document and then load the URL of
Google Docs using the WebView :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
WebView webView=new WebView(MainActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
//---you need this to prevent the webview from
// launching another browser when a url
// redirection occurs---
webView.setWebViewClient(new Callback());
String pdfURL = "http://dl.dropboxusercontent.com/u/37098169/Course%20Brochures/AND101.pdf";
webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" + pdfURL);
setContentView(webView);
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(
WebView view, String url) {
return(false);
}
}