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?
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
I have a Recycler View which uses AsyncTask to populate UI.
Currently it retrieves all the data from the DB and displays it in one shot, but
I want to retrieve only 15 records in one go and after the scroll ends I want to load more 15 records and so on...can anybody please help. I have pasted the code below:
FeedActivity.java
package com.bbau.ankit.test_splash;
import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Window;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class FeedListActivity extends Activity {
private static final String TAG = "RecyclerViewExample";
private List<FeedItem> feedItemList = new ArrayList<FeedItem>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Allow activity to show indeterminate progressbar */
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.news);
/* Initialize recyclerview */
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(Color.BLACK).build());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
/*Downloading data from below url*/
final String url = "http://192.168.170.72/bbau_news.php?before=1&after=5";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(FeedListActivity.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("NEWS");
/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedItem>();
}
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("news_desc"));
item.setDescription(post.optString("Date"));
item.setUrl(post.optString("News"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
MyRecyclerAdapter.java
package com.bbau.ankit.test_splash;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.style.AlignmentSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by Ankit on 8/14/2015.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<FeedListRowHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public FeedListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
FeedListRowHolder mh = new FeedListRowHolder(v);
mh.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("List Size", Integer.toString(getItemCount()));
TextView redditUrl = (TextView) v.findViewById(R.id.url);
String postUrl = redditUrl.getText().toString();
Log.d("The URL:", postUrl);
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("url", postUrl);
mContext.startActivity(intent);
}
});
return mh;
}
#Override
public void onBindViewHolder(FeedListRowHolder feedListRowHolder, int i) {
final FeedItem feedItem = feedItemList.get(i);
feedListRowHolder.title.setText(Html.fromHtml(feedItem.getTitle()));
feedListRowHolder.description.setText(feedItem.getDescription());
feedListRowHolder.url.setText(feedItem.getUrl());
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
Of course you can use Recycler view and EndlessScrool as a combination like this..
Here is a sample
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
Log.v("...", "Last Item Wow !");
}
}
}
});
Don't forget to add
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
Here is a Github example: EndlessRecyclerOnScrollListener