I'm trying to make an inventory apps to save item by item into internal storage. Here is my layout. The problem is it possible to save arraylist into document text file / other internal storage? Because fos.write(listitem.getBytes()); should be in Int. Here is my code from Activity2
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
public static final String extraint = "1";
public static final String namabarang = "2";
public static final String jumlahstock ="3";
public static final String FILE_NAME="example.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void onBtnClick(View view){
TextView plain1 = findViewById(R.id.NamaBarang);
TextView plain2 = findViewById(R.id.SKU);
TextView plain3 = findViewById(R.id.JumlahStok);
TextView plain4 = findViewById(R.id.HargaBeli);
TextView plain5 = findViewById(R.id.HargaJual);
Intent intent = new Intent(this,MainActivity3.class);
String x = "1";
String text = plain1.getText().toString();
FileOutputStream fos = null;
Item m1 = new Item("a","1");
Item m2 = new Item("b","2");
Item m3 = new Item("c","3");
ArrayList<Item> listitem = new ArrayList<>();
listitem.add(m1);
listitem.add(m2);
listitem.add(m3);
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(listitem.getBytes());
Toast.makeText(this,"Saved to" +getFilesDir() + "/" + FILE_NAME,Toast.LENGTH_LONG).show();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(fos != null){
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
intent.putExtra(extraint,x);
intent.putExtra(FILE_NAME,text);
intent.putExtra(namabarang,plain1.getText().toString());
intent.putExtra(jumlahstock,plain3.getText().toString());
startActivity(intent);
}
}
Here is another code from Activity 3
package com.example.java;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.renderscript.ScriptGroup;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListView;
import org.w3c.dom.Element;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity3 extends AppCompatActivity {
private static final String Tag = "MainAcitivity3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Log.d(Tag, "onCreate: Started.");
ListView mListView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
String[] barang = new String[20];
String[] jumlah = new String[20];
ArrayList<Item> itemlist = new ArrayList<Item>();
int loop=0;
barang[loop] = intent.getStringExtra(MainActivity2.namabarang);
jumlah[loop] = intent.getStringExtra(MainActivity2.jumlahstock);
loop++;
FileInputStream fis = null;
StringBuilder sb = new StringBuilder();
try {
fis = openFileInput(MainActivity2.FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String text;
while ((text = br.readLine()) != null){
sb.append(text).append("\n");
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
String result=sb.toString();
for(int i=0;i<loop;i++) {
Item sparepart = new Item(result, result);
itemlist.add(sparepart);
}
PersonListAdapter adapter = new PersonListAdapter(this, R.layout.adapter_view_layout,itemlist);
mListView.setAdapter(adapter);
String number = intent.getStringExtra(MainActivity2.extraint);
if(number != null) {
FrameLayout lay = (FrameLayout) findViewById(R.id.frames);
if (number.equals("1")) {
lay.setVisibility(View.INVISIBLE);
mListView.setVisibility(View.VISIBLE);
} else {
}
}
else{}
}
public void onBtnClick (View view){
Intent intent = new Intent(this,MainActivity2.class);
startActivity(intent);
}
}
The apps supposed to save one item by item into the internal storage which where i try to utilize array to save the into the internal storage, but it it possible to save and read array to internal storage?
Related
I am a beginner in Android studio and I am trying to send an array list to a list view. I know that I am passing the correct info from my main activity to the second activity and that it is received properly in the second activity. My issue is coming in when I try to pass the array list "filteredlist" to the array adapter "arradapter" to then send to list view. It is giving me this error: java.lang.NullPointerException: "Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference."
I am sure I am missing something, but I am not sure what.
I am aware the code isn't perfect, and I plan on streamlining it later.
Second activity:
package com.example.charityfinder;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class ResultsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
ArrayList<NationalCharity> filteredlist = (ArrayList<NationalCharity>) getIntent().getSerializableExtra("Filtered List");
Log.d("DEBUG", "Second Activity: " + filteredlist);//prints out list here
ListView dataresults = (ListView) findViewById(R.id.dataresults);
ArrayAdapter<NationalCharity> arradapter = new ArrayAdapter<NationalCharity>(this, R.layout.item_view, R.id.itemTextView, filteredlist);
dataresults.setAdapter(arradapter);
}
}
Main Activity:
package com.example.charityfinder;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//references to buttons and other controls
Button submitbtn;
RadioButton medicalRadio, envirRadio, hserviceRadio, educationRadio, publicaRadio,
cultureRadio, domesticvRadio, hrightsRadio, homelessRadio, religionRadio, youthRadio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readcharitydata();
medicalRadio = findViewById(R.id.medicalRadio);
envirRadio = findViewById(R.id.envirRadio);
hserviceRadio = findViewById(R.id.hserviceRadio);
educationRadio = findViewById(R.id.educationRadio);
publicaRadio = findViewById(R.id.publicaRadio);
cultureRadio = findViewById(R.id.cultureRadio);
domesticvRadio = findViewById(R.id.domesticvRadio);
hrightsRadio = findViewById(R.id.hrightsRadio);
homelessRadio = findViewById(R.id.homelessRadio);
religionRadio = findViewById(R.id.religionRadio);
youthRadio = findViewById(R.id.youthRadio);
submitbtn = findViewById(R.id.submitbtn);
submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openNewActivity();
}
});
}
String category;
public void onRadioButtonClicked(View view) {
if (medicalRadio.isChecked()) {
category = "Medical";
} else if (envirRadio.isChecked()) {
category = "Environmental_Animal";
} else if (hserviceRadio.isChecked()) {
category = "Human_Services";
} else if (educationRadio.isChecked()) {
category = "Education";
} else if (publicaRadio.isChecked()) {
category = "Public_Affairs";
} else if (cultureRadio.isChecked()) {
category = "Culture_Arts_Humanities";
} else if (domesticvRadio.isChecked()) {
category = "Domestic_Violence";
} else if (hrightsRadio.isChecked()) {
category = "Human_Rights";
} else if (homelessRadio.isChecked()) {
category = "Homelessness";
} else if (religionRadio.isChecked()) {
category = "Religious";
} else if (youthRadio.isChecked()) {
category = "Youth";
}
filterCharity(category);
}
private List<NationalCharity> charities = new ArrayList<>();
private void readcharitydata() {
InputStream is = getResources().openRawResource(R.raw.charities);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
//ignore headers
reader.readLine();
while ((line = reader.readLine()) != null) {
//split by comma
String[] token = line.split(",");
//Read data
NationalCharity charity = new NationalCharity();
charity.setCharity_name(token[0]);
charity.setCategory(token[1]);
charity.setWeb_address(token[2]);
charity.setAddress(token[3]);
charity.setCity(token[4]);
charity.setState(token[5]);
charity.setZipcode(token[6]);
charity.setMission_statement(token[7]);
charities.add(charity);
}
} catch (IOException e) {
Log.wtf("Error", "Error reading data file" + line, e);
e.printStackTrace();
}
}
private ArrayList<NationalCharity> filtered = new ArrayList<>();
//needing to filter here from the charities list
private void filterCharity(String type) {
for (NationalCharity charity : charities) {
if (charity.getCategory().equals(type)) {
filtered.add(charity);
Log.d("DEBUG", "Just created: " + filtered);
}
}
}
public void openNewActivity() {
Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
intent.putExtra("Filtered List", filtered);
Log.d("DEBUG", "Passing: " + filtered);
startActivity(intent);
}
}
I am trying to import data from a csv file but my application crashes everytime. Below is my code that I have written. I receive no errors.
My main aim is to import data from the specified csv file and put in the variable called count_car. I want to show the value in the text box when I click the button. But I could not import the data from csv file.
package com.example.deneme2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.String;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text_zeros = findViewById(R.id.TextNumberZero);
TextView text_ones = findViewById(R.id.TextNumberOne);
TextView textView = findViewById(R.id.textView);
TextView textView1 = findViewById(R.id.textView2);
Button button = findViewById(R.id.button);
String path = "C:\\Users\\baran\\Desktop\\FALL 2020\\ELEC491\\deneme\\11111111111\\venv\\numberofcars.csv";
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BufferedReader csvReader = null;
try {
csvReader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String count_car = null;
int counting =0;
while (true) {
try {
if (!((count_car = csvReader.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
//String[] data = count_car.split(",");
String count_cars = count_car;
int count_park= 100;
String countpark = String.valueOf(count_park);
String countcars = String.valueOf(count_cars);
text_ones.setText(countpark);
text_zeros.setText(countcars);
counting = counting +1 ;
if (counting == 50);
break;
}
}
});
}
}
EDIT 1
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text_cars = findViewById(R.id.textCars);
readData();
String count_park = Arrays.toString(number_of_cars.get(1));
text_cars.setText(count_park);
}
private List<String[]> number_of_cars = new ArrayList<>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
I have changed the code. Now I am using different method. But the app starts to crash again. Is there any opinion? Thanks for answers.
EDIT 2
package com.example.exceldeneme;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.String;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class MainActivity<number_cars> extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = findViewById(R.id.video_view);
Button button = findViewById(R.id.button);
TextView text_cars = findViewById(R.id.textEmpty);
TextView text_total_lots = findViewById(R.id.textTotalLots);
readData();
int number_of_park = 100;
text_total_lots.setText(String.valueOf(number_of_park));
int counter = 0;
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.camera_out;
Uri uri = Uri.parse(videoPath);
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);
//Log.d("Selam","This is my message"+ number_of_cars.get(0)[0]);
//String count_park = number_of_cars.get(0)[2];
//text_cars.setText(count_park);
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int counter = 0;
for (String i : number_of_cars.get(0)){
counter = counter + 1 ;
}
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
text_cars.setText(count_park);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
}
});
}
private ArrayList<String[]> number_of_cars = new ArrayList<String[]>();
private void readData() {
InputStream is = getResources().openRawResource(R.raw.numberofcars);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
String line = "";
try {
while(((line = reader.readLine()) != null)) {
String[] tokens = line.split(",");
number_of_cars.add(tokens);
Log.d("MyActivity","Just created"+ Arrays.toString(tokens));
}
}
catch (IOException e) {
Log.wtf("MyActivity","Error reading data file on line" + line, e);
e.printStackTrace();
}
}
}
My final code is here. I have solved my problems and imported data from csv file. I have used videoview to show video. Now I am trying to solve the delay problem.
I want the below for loop function to wait for 1 second or 50 ms. But I could not find the solution.
for (int i = 1; i < counter-1;i= i +1){
String count_park = number_of_cars.get(0)[i];
text_cars.setText(count_park);
//SystemClock.sleep(1000); //ms
Log.d("Selam","SORUN YOK");
}
If anyone can help, I appreciate it :) Thanks for your answers.
I am trying to build an app for class and am having trouble with handling data that is gathered in another thread. The data does not seems to being passed through the handlers handleMessage method.
This is my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
ArrayList<Book> names;
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
// Handler bookHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
names = new ArrayList<Book>();
final EditText searchBar = findViewById(R.id.searchbar);
final Handler bookHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
String response = (String) msg.obj;
try{
JSONArray tmp = new JSONArray(response);
for(int i = 0; i < tmp.length(); i++){
JSONObject a = tmp.getJSONObject(i);
int id = a.getInt("book_id");
String title = a.getString("title");
Log.d("BOOK_id", a.getInt("book_id")+"");
String author = a.getString("author");
int published = a.getInt("published");
String coverUrl = a.getString("cover_url");
Book book = new Book(id,title,author,published,coverUrl);
names.add(book);
}
} catch (Exception e){
Log.d("FAIL", e.toString());
}
return false;
}
});
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
Log.d("Handler", response);
Message msg = Message.obtain();
msg.obj = response;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.e("Fail", e.toString());
}
}
};
t.start();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
JSONArray bookOBJ= new JSONArray(response);
Message msg = Message.obtain();
msg.obj = bookOBJ;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.d("Fail", e.toString());
}
}
};
t.start();
}
});
}
The code is suppose to get data from an api and then in the handleMessage method it is suppose to parse the data into a book object that contains two int and three string variables. The problem is that the handler never executes any code.
The execution should be that the debugger log should have the response string with the data from the API and then the id of every book in the JSON file, but it only has the data from the api displayed.
I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of
currently I am developing an Android Application (Native). In my application, I need to load many images and that cause a problem.
The problem is:
1. When I first open the app after deploy it on my android phone, it works fine. However, after I close the application (by clicking the back button), and then I open the application again, the app closed unexpectedly. When I check the logcat, I found out that it was closed because of OutOfMemory error.
2. Second problem: after I open my application, and I go to the next page, it also give me OutOfMemory error.
I guess, the problem occur because I load too many images. After I do some searching on the internet, it suggest me to do System.gc
But unfortunately, it did not work for me.
Here is my code:
Homepage_Activity.java
package dev.com.friseur;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.friseur.insert.AddComment;
import dev.friseur.rest.Photo;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class HomePage extends ActionBarActivity {
private String p_id = "1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Intent intent = getIntent();
int size = Integer.parseInt(intent.getStringExtra("size")) * 2;
LinearLayout hp = (LinearLayout)findViewById(R.id.homepage);
Photo photo = new Photo(hp, this, size);
photo.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The photo.execute() code will call an asynchronous task. Here it is:
package dev.friseur.rest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import dev.com.friseur.RecognizeFace;
import dev.com.friseur.ViewPhoto;
import dev.friseur.insert.AddComment;
import dev.friseur.insert.AddLike;
import android.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.SystemClock;
import android.text.InputFilter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Photo extends AsyncTask<String, Void, String>{
private Context context;
private LinearLayout homepage;
private int size;
private String sessionUname;
private String sessionUserid;
private File file;
private ArrayList<String> photo_id;
private ArrayList<String> imageName;
private ArrayList<String> date_upload;
private ArrayList<String> url_original;
private ArrayList<String> url_with_hair;
private ArrayList<String> caption;
private ArrayList<String> user_id;
private ArrayList<String> username;
private ArrayList<JSONArray> comments;
private ArrayList<Integer> totalcomment;
public Photo(LinearLayout homepage, Context context, int size){
this.context = context;
this.homepage = homepage;
this.size = size;
this.sessionUname = "testuser";
this.sessionUserid = "1";
photo_id = new ArrayList<String>();
imageName = new ArrayList<String>();
date_upload = new ArrayList<String>();
url_original = new ArrayList<String>();
url_with_hair = new ArrayList<String>();
caption = new ArrayList<String>();
user_id = new ArrayList<String>();
username = new ArrayList<String>();
comments = new ArrayList<JSONArray>();
totalcomment = new ArrayList<Integer>();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.43.8:8080/FriseurRest/WebService/GetPhotos");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
JSONObject json_data = new JSONObject(line);
photo_id.add(json_data.getString("p_id"));
imageName.add(json_data.getString("imagename"));
date_upload.add(json_data.getString("date_upload"));
url_original.add(json_data.getString("url_original"));
url_with_hair.add(json_data.getString("url_with_hair"));
caption.add(json_data.getString("caption"));
user_id.add(Integer.toString(json_data.getInt("user_id")));
username.add(json_data.getString("username"));
comments.add(json_data.getJSONArray("photoComments"));
totalcomment.add(json_data.getInt("total_comment"));
i++;
}
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onDestroy() {
System.gc();
Runtime.getRuntime().gc();
}
protected void onPostExecute(String p_id) {
for(int i = 0; i < imageName.size(); i++){
final int j = i;
LinearLayout photo = new LinearLayout(context);
photo.setOrientation(LinearLayout.VERTICAL);
photo.setPadding(0, 0, 0, 50);
LinearLayout postdesc = createPostDesc(i);
file = new File(Environment.getExternalStorageDirectory() + "/" + url_original.get(i), imageName.get(i));
Uri imgUri = Uri.fromFile(file);
ImageView img = new ImageView(context);
img.setImageURI(imgUri);
img.setMaxWidth(size);
img.setMinimumWidth(size);
img.setMaxHeight(size);
img.setMinimumHeight(size);
TextView tv = new TextView(context);
tv.setText(caption.get(i));
final LinearLayout showcomment = new LinearLayout(context);
showcomment.setOrientation(LinearLayout.VERTICAL);
showcomment.setPadding(0, 10, 0, 10);
try {
if(totalcomment.get(i) > 5){
LinearLayout more = new LinearLayout(context);
more.setPadding(0, 0, 0, 5);
TextView viewmore = new TextView(context);
viewmore.setTextColor(Color.GRAY);
viewmore.setText("View More Comments");
viewmore.setClickable(true);
viewmore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, ViewPhoto.class);
intent.putExtra("size", size);
intent.putExtra("p_id", photo_id.get(j));
intent.putExtra("imageName", imageName.get(j));
intent.putExtra("date_upload", date_upload.get(j));
intent.putExtra("url_original", url_original.get(j));
intent.putExtra("url_with_hair", url_with_hair.get(j));
intent.putExtra("caption", caption.get(j));
intent.putExtra("user_id", user_id.get(j));
intent.putExtra("username", username.get(j));
context.startActivity(intent);
}
});
more.addView(viewmore);
showcomment.addView(more);
}
for(int k = 0; k < comments.get(i).length(); k++) {
//ArrayList<String> photoCom = comments.get(k);
//int userCom = photoCom.length();
JSONObject photoCom = comments.get(i).getJSONObject(k);
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(photoCom.getString("com_username"));
TextView showcom = new TextView(context);
showcom.setText(photoCom.getString("com_desc"));
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
} catch (Exception e) {
}
LinearLayout addcomment = createAddComment(i);
final EditText et_comment = new EditText(context);
et_comment.setHint("Add Comment");
et_comment.setMaxWidth(size*3/4);
et_comment.setMinimumWidth(size*3/4);
int maxLength = 150;
et_comment.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
Button button_comment = new Button(context);
button_comment.setText("Post");
button_comment.setTextSize(15);
button_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String com = et_comment.getText().toString();
try{
AddComment ac = new AddComment(sessionUserid, com, photo_id.get(j));
ac.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
LinearLayout ll_comment = new LinearLayout(context);
ll_comment.setPadding(0, 0, 0, 5);
TextView uname = new TextView(context);
uname.setTextColor(Color.BLUE);
uname.setPadding(0,0,3,0);
uname.setText(sessionUname);
TextView showcom = new TextView(context);
showcom.setText(com);
showcom.setAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in));
et_comment.setText("");
ll_comment.addView(uname);
ll_comment.addView(showcom);
showcomment.addView(ll_comment);
}
});
addcomment.addView(et_comment);
addcomment.addView(button_comment);
addcomment.setVisibility(View.GONE);
LinearLayout social = createSocialFeature(i, addcomment, et_comment);
photo.addView(postdesc);
photo.addView(img);
photo.addView(tv);
photo.addView(showcomment);
photo.addView(social);
photo.addView(addcomment);
homepage.addView(photo);
}
}
private LinearLayout createPostDesc(int i){
LinearLayout postdesc = new LinearLayout(context);
postdesc.setOrientation(LinearLayout.VERTICAL);
postdesc.setMinimumHeight(40);
TextView uname = new TextView(context);
uname.setText("#"+username.get(i));
TextView timeupload = new TextView(context);
timeupload.setText(date_upload.get(i));
if(i>0){
View separator = new View(context);
separator.setMinimumHeight(1);
separator.setBackgroundColor(Color.BLACK);
separator.setPadding(0, 10, 0, 0);
postdesc.addView(separator);
}
postdesc.addView(uname);
postdesc.addView(timeupload);
return postdesc;
}
private LinearLayout createSocialFeature(final int i, final LinearLayout addcomment, final EditText et_comment){
LinearLayout social = new LinearLayout(context);
social.setOrientation(LinearLayout.HORIZONTAL);
social.setMinimumHeight(40);
social.setPadding(0,10,10,0);
TextView tv_comment = new TextView(context);
tv_comment.setText("Add Comment");
tv_comment.setPadding(0, 0, 15, 0);
tv_comment.setClickable(true);
tv_comment.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addcomment.setVisibility(View.VISIBLE);
et_comment.setFocusableInTouchMode(true);
et_comment.setFocusable(true);
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0));
et_comment.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0));
}
});
final TextView tv_like = new TextView(context);
tv_like.setText("Like");
tv_like.setClickable(true);
tv_like.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String like = tv_like.getText().toString();
try{
AddLike lk = new AddLike(sessionUserid, like, photo_id.get(i));
lk.execute();
}
catch(Exception e){
CharSequence text = "Internet Connection Unstable. Please Try Again!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if(like.equals("Like")){
tv_like.setText("Unlike");
}
else{
tv_like.setText("Like");
}
}
});
social.addView(tv_comment);
social.addView(tv_like);
return social;
}
private LinearLayout createAddComment(int i){
LinearLayout addcomment = new LinearLayout(context);
addcomment.setId(Integer.parseInt(photo_id.get(i)));
addcomment.setOrientation(LinearLayout.HORIZONTAL);
addcomment.setPadding(0,20,0,0);
return addcomment;
}
}
This asynchronous task used to call the rest service.
What is wrong with my code? And how can I solve the OutOfMemory error. Any help would be appreciated. Thanks in advance
You can use lazyloading to fix this and follow this url for lazy loading:
https://github.com/nostra13/Android-Universal-Image-Loader
You can see my answer here.It will be useful to handle your bitmap efficiently.
How to make application more responsive which uses several bitmaps?