i am making an application where data is being saved in the database.i am lacking in displaying the data in the recyclerview using recyclerview adapter.don't know what code should be written. please check.
here is my files: MainActivity.java
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView applist;
ArrayList<Guides> guides;
GuideAdapter adapter;
GuideDB guideDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
adapter = new GuideAdapter(this,guides);
applist.setAdapter(adapter);
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_add){
startActivity(new Intent(MainActivity.this,PostActivity.class));
}
return super.onOptionsItemSelected(item);
}
}
PostActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PostActivity extends AppCompatActivity {
public ImageButton mSelectImage;
public EditText mPostTitle;
public EditText mPostDesc;
public EditText mPostAddress;
public Button mSubmitbtn;
private static final int GALLERY_REQUEST= 1;
GuideDB guideDB;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
guideDB = new GuideDB(this);
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostTitle = (EditText) findViewById(R.id.titleField);
mPostDesc = (EditText) findViewById(R.id.descField);
mPostAddress = (EditText) findViewById(R.id.addressField);
mSubmitbtn = (Button) findViewById(R.id.submitButton);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GALLERY_REQUEST);
}
});
mSubmitbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if(!mPostTitle.getText().toString().isEmpty() && !mPostDesc.getText().toString().isEmpty() && !mPostAddress.getText().toString().isEmpty())
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,50,outputStream);
byte[] byteArray = outputStream.toByteArray();
try {
guideDB.addGuide(mPostTitle.getText().toString(),
mPostDesc.getText().toString(),
mPostAddress.getText().toString(),byteArray
);
Toast.makeText(getApplicationContext(),"Added successfully!",Toast.LENGTH_LONG).show();
}catch (Exception e){e.printStackTrace();}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri mimageUri = data.getData();
try {
InputStream inputstream = getContentResolver().openInputStream(mimageUri);
bitmap = BitmapFactory.decodeStream(inputstream);
mSelectImage.setImageBitmap(bitmap);
}catch (FileNotFoundException e){e.printStackTrace();}
}
}
}
GuideDB.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideDB extends SQLiteOpenHelper {
private static final int DATABASE_VERSION= 1;
private static final String DATABASE_NAME= "guide_db";
private static final String TABLE_NAME = "GUIDE_LIST";
private static String GUIDE_ID = "guide_id";
private static String GUIDE_TITLE = "guide_title";
private static String GUIDE_DESC = "guide_desc";
private static String GUIDE_ADDRESS = "guide_address";
private static String GUIDE_IMG = "guides_image";
public GuideDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "("
+ GUIDE_ID + "INTEGER PRIMARY KEY AUTOINCREMENT"
+ GUIDE_TITLE + "TEXT"
+ GUIDE_DESC + "TEXT"
+ GUIDE_ADDRESS + "TEXT"
+ GUIDE_IMG + "BLOB" + ")";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public void addGuide (String title,String desc,String address,byte[] image){
SQLiteDatabase gdb = getWritableDatabase();
try
{
String sql = "INSERT INTO GUIDE_LIST VALUES(NULL,?,?,?)";
SQLiteStatement statement = gdb.compileStatement(sql);
statement.clearBindings();
statement.bindString(1,title);
statement.bindString(2,desc);
statement.bindString(3,address);
statement.bindBlob(4,image);
statement.execute();
}catch (Exception e){e.printStackTrace();}
}
public Cursor getGuides(String sql){
SQLiteDatabase gdb = getReadableDatabase();
return gdb.rawQuery(sql,null);
}
}
GuideAdapter.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by 291 on 14.12.2017.
*/
public class GuideAdapter extends RecyclerView.Adapter<GuideAdapter.ViewHolder> {
private Context ctx;
private ArrayList<Guides> guidelist;
public GuideAdapter(Context ctx, ArrayList<Guides> guidelist) {
this.ctx = ctx;
this.guidelist = guidelist;
}
#Override
public GuideAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.guide_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(GuideAdapter.ViewHolder holder, int position) {
Guides guides = guidelist.get(position);
holder.psttitle.setText(guides.getPost_title());
holder.pstdesc.setText(guides.getPost_desc());
holder.pstaddres.setText(guides.getPost_address());
byte [] postimg = guides.getPost_image();
Bitmap bitmap = BitmapFactory.decodeByteArray(postimg,0,postimg.length);
holder.pstimg.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return guidelist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public ImageView pstimg;
public TextView psttitle;
public TextView pstdesc;
public TextView pstaddres;
public int id;
public ViewHolder(View itemView) {
super(itemView);
pstimg = (ImageView) itemView.findViewById(R.id.post_image);
psttitle = (TextView) itemView.findViewById(R.id.post_title);
pstdesc = (TextView) itemView.findViewById(R.id.post_title);
pstaddres = (TextView) itemView.findViewById(R.id.post_address);
}
}
}
Guides.java
public class Guides {
private int guide_id;
private String post_title,post_desc,post_address;
private byte [] post_image;
public Guides(int guide_id, String post_title, String post_desc, String post_address, byte [] post_image) {
this.guide_id = guide_id;
this.post_title = post_title;
this.post_desc = post_desc;
this.post_address = post_address;
this.post_image = post_image;
}
public int getGuide_id() {
return guide_id;
}
public void setGuide_id(int guide_id) {
this.guide_id = guide_id;
}
public String getPost_title() {
return post_title;
}
public void setPost_title(String post_title) {
this.post_title = post_title;
}
public String getPost_desc() {
return post_desc;
}
public void setPost_desc(String post_desc) {
this.post_desc = post_desc;
}
public String getPost_address() {
return post_address;
}
public void setPost_address(String post_address) {
this.post_address = post_address;
}
public byte[] getPost_image() {
return post_image;
}
public void setPost_image(byte[] post_image) {
this.post_image = post_image;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ugurcangursen.guideappsqlite.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/app_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="10dp"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_post.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ugurcangursen.guideappsqlite.PostActivity">
<ImageButton
android:id="#+id/imageSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:background="#00ffffff"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<EditText
android:id="#+id/titleField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageSelect"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Title..."
android:inputType="textPersonName"
android:padding="10dp"
android:singleLine="true" />
<EditText
android:id="#+id/descField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/titleField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Post Description..."
android:inputType="textMultiLine"
android:padding="10dp" />
<EditText
android:id="#+id/addressField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/descField"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/input_outline"
android:hint="Adres..."
android:inputType="textMultiLine"
android:padding="10dp" />
<Button
android:id="#+id/submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#color/colorPrimary"
android:text="SUBMIT POST"
android:textColor="#android:color/white" />
</RelativeLayout>
guide_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:srcCompat="#drawable/add_btn" />
<TextView
android:id="#+id/post_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:textSize="16dp"
android:textStyle="bold"
tools:text="Başlık" />
<TextView
android:id="#+id/post_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Açıklama" />
<TextView
android:id="#+id/post_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
tools:text="Adres" />
</LinearLayout>
</android.support.v7.widget.CardView>
I'm not reviewing all the code you have posted. However, it does appear that you are setting the adpater with an empty source (guides), so it would then display nothing.
The following version of the onCreate method may result in the data being displayed
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideDB = new GuideDB(this);
guides = new ArrayList<>();
applist = (RecyclerView) findViewById(R.id.app_list);
applist.setHasFixedSize(true);
applist.setLayoutManager(new LinearLayoutManager(this));
//adapter = new GuideAdapter(this,guides); //<<<< MOVED
//applist.setAdapter(adapter); //<<<< MOVED
try {
Cursor cursor = guideDB.getGuides("SELECT * FROM GUIDE_LIST");
while (cursor.moveToNext()){
int guide_id = cursor.getInt(0);
String post_tile = cursor.getString(1);
String post_desc = cursor.getString(2);
String post_address = cursor.getString(3);
byte [] post_image = cursor.getBlob(4);
Guides g = new Guides(guide_id,post_tile,post_desc,post_address,post_image);
guides.add(g);}
}catch (Exception e){e.printStackTrace();}
adapter = new GuideAdapter(this,guides); //<<<< MOVED
applist.setAdapter(adapter); //<<<< MOVED
}
Related
To save this PDF I have added a while loop where the last letter has added a specific number from 0 to n in parentheses. When I save the first PDF it is saved as myPDFfile.pdf then the second pdf will be saved as myPDFFile(1).pdf but when I save the third pdf it will be saved as myPDFFile(1)(1).pdf
but I want this pdf to save as myPDFfile(2).pdf.
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
Button button;
private TextToSpeech textToSpeech;
private String stringResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
button = findViewById(R.id.btn1);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
textToSpeech.setLanguage(Locale.US);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
}
private void textRecognizer() {
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void buttonStart(View view) {
setContentView(R.layout.surface);
Button capture = findViewById(R.id.capture);
capture.setOnClickListener(v -> capture());
textRecognizer();
}
public void createMyPDF(View view) {
PdfDocument myPdfDocument = new PdfDocument();
PdfDocument.PageInfo myPageInfo = new PdfDocument.PageInfo.Builder(300, 600, 1).create();
PdfDocument.Page myPage = myPdfDocument.startPage(myPageInfo);
Paint myPaint = new Paint();
String myString = textView.getText().toString();
int x = 10, y = 25;
for (String line : myString.split("\n")) {
myPage.getCanvas().drawText(line, x, y, myPaint);
y += myPaint.descent() - myPaint.ascent();
}
myPdfDocument.finishPage(myPage);
String myFilePath = Environment.getExternalStorageDirectory().getPath() + "/myPDFFile.pdf";
File myFile = new File(myFilePath);
while (myFile.exists()) {
int i = 0;
i++;
myFile = new File(myFile.toString().replace("myPDFFile", "myPDFFile (" + i + ")"));
}
try {
myPdfDocument.writeTo(new FileOutputStream(myFile));
} catch (Exception e) {
e.printStackTrace();
textView.setText("ERROR");
}
myPdfDocument.close();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
XML Code:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
tools:context=".MainActivity"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="-2dp"
android:layout_marginTop="-4dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginStart="-4dp"
android:layout_marginTop="-2dp"
android:background="#color/black"
android:gravity="center"
android:text="OCR READER FOR VISUALLY IMPARED PEOPLES"
android:textColor="#color/white"
android:textIsSelectable="true"
android:textSize="20dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="8dp" />
</ScrollView>
<Button
android:id="#+id/btn"
android:layout_width="407dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="0dp"
android:layout_marginBottom="24dp"
android:onClick="buttonStart"
android:text="Click here"
android:textSize="20dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:layout_alignBottom="#+id/btn"
android:layout_alignParentStart="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp"
android:onClick="createMyPDF"
android:text="Create PDF"
android:textSize="20dp" />
</RelativeLayout>
surface.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="378dp"
android:layout_height="628dp"
android:layout_marginStart="16dp"
android:layout_marginTop="4dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:id="#+id/capture"
android:layout_marginHorizontal="32dp"
android:layout_marginBottom="32dp"
android:text="Capture"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Problem
I am creating music player using android studio.
Everything was fine until I added search filter to search songs.
Search filter returns the song right but when I click on searched result wrong music file is opened however the music name shown on player activity is right but the song played is first song of list every time .
Example
There are 4 song items named: A,B,C,D
When searched C ,filtered result C is shown. But when Clicked on it Song name C is shown but Song A is played.
This is really frustrating.
Main Activity.java
package com.example.musicplayer2;
import android.Manifest;
import android.content.Intent;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static boolean shuffleBol = false;
static boolean loopBol = false;
ListView listView;
String[] items;
ArrayAdapter<String> myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySongs();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
if (files != null){
for (File singlefile : files)
{
if (singlefile.isDirectory() && !singlefile.isHidden())
{
arrayList.addAll(findSong(singlefile));
}
else
{
if (singlefile.getName().endsWith(".mp3") && !singlefile.getName().startsWith("."))
{
arrayList.add(singlefile);
}
}
}
}
return arrayList;
}
void displaySongs()
{
ArrayList<File> mysongs;
mysongs = findSong(Environment.getExternalStorageDirectory());
items = new String[mysongs.size()];
for (int i=0; i < mysongs.size(); i++)
{
items[i] = mysongs.get(i).getName().replace(".mp3","");
}
// ArrayAdapter<String> myAdapter;
myAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String songName = (String) listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)
.putExtra("songs",mysongs)
.putExtra("songname",songName)
.putExtra("position",position));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
main activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/listViewSong"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="8dp"
>
</ListView>
</RelativeLayout>
PlayerActivity.java
package com.example.musicplayer2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import static com.example.musicplayer2.MainActivity.loopBol;
import static com.example.musicplayer2.MainActivity.shuffleBol;
public class PlayerActivity extends AppCompatActivity {
ImageView btnplay,btnnext,btnprev,btnshuffle,btnloop;
TextView txtsname,txtstart,txtstop;
SeekBar seekmusic;
String sname;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList<File> mySongs;
Thread updateseekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Player");
btnprev = findViewById(R.id.btnprev);
btnnext = findViewById(R.id.btnnext);
btnplay = findViewById(R.id.playbtn);
btnshuffle = findViewById(R.id.btnshuffle);
btnloop = findViewById(R.id.btnloop);
txtsname = findViewById(R.id.txtsn);
txtstart = findViewById(R.id.txtstart);
txtstop = findViewById(R.id.txtstop);
seekmusic = findViewById(R.id.seekbar);
// if a media player is already running then.
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList)bundle.getParcelableArrayList("songs");
String songName = i.getStringExtra("songname");
position = bundle.getInt("position",0);
txtsname.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString());
sname = mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
mediaPlayer.start();
updateseekbar = new Thread()
{
#Override
public void run() {
int totalDuration = mediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition<totalDuration)
{
try {
sleep(500);
currentPosition = mediaPlayer.getCurrentPosition();
seekmusic.setProgress(currentPosition);
}
catch (InterruptedException | IllegalStateException e)
{
e.printStackTrace();
}
}
}
};
seekmusic.setMax(mediaPlayer.getDuration());
updateseekbar.start();
seekmusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime = createTime(mediaPlayer.getCurrentPosition());
txtstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
// click Listener ON PLAY button
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying())
{
btnplay.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
else
{
btnplay.setBackgroundResource(R.drawable.pause);
mediaPlayer.start();
}
}
});
// click Listener ON next button
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol)
{
position=((position+1)%mySongs.size());
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click Listener ON previous button
btnprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol){
position=((position-1)<0)?(mySongs.size()-1):(position-1);
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click listener for shuffle btn
btnshuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (shuffleBol){
shuffleBol=false;
btnshuffle.setImageResource(R.drawable.shuffle_off);
}
else {
shuffleBol=true;
btnshuffle.setImageResource(R.drawable.shuffle_on);
}
}
});
// click listener for loop btn
btnloop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (loopBol){
loopBol=false;
btnloop.setImageResource(R.drawable.loop_off);
}
else {
loopBol=true;
btnloop.setImageResource(R.drawable.loop_on);
}
}
});
// next Listener ON song completion
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnnext.performClick();
}
});
}
public String createTime(int duration)
{
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10)
{
time+="0";
}
time+=sec;
return time;
}
private int getRandom(int i) {
Random random= new Random();
return random.nextInt(i+1);
}
}
PlayerActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:background="#drawable/bg"
android:orientation="vertical"
android:weightSum="10"
tools:context=".PlayerActivity"
android:baselineAligned="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="7"
android:gravity="center"
android:orientation="vertical"
tools:ignore="Suspicious0dp,UselessParent">
<TextView
android:id="#+id/txtsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="#string/song_name"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="italic">
</TextView>
<ImageView
android:id="#+id/imageview"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginBottom="8dp"
android:src="#drawable/logo">
</ImageView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<SeekBar
android:id="#+id/seekbar"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:layout_marginBottom="40dp">
</SeekBar>
<TextView
android:id="#+id/txtstart"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="-17dp"
android:layout_toLeftOf="#+id/seekbar"
android:text="0:00"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
<TextView
android:id="#+id/txtstop"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="false"
android:layout_centerInParent="true"
android:layout_marginLeft="-14dp"
android:layout_marginRight="20dp"
android:layout_toRightOf="#+id/seekbar"
android:text="#string/_4_10"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="98dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/playbtn"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:background="#drawable/pause" />
<ImageView
android:id="#+id/btnnext"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/playbtn"
android:background="#drawable/next" />
<ImageView
android:id="#+id/btnprev"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/playbtn"
android:background="#drawable/previous" />
<ImageView
android:id="#+id/btnshuffle"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/btnprev"
android:layout_marginTop="85dp"
android:layout_marginRight="35dp"
android:background="#drawable/shuffle_off"/>
<ImageView
android:id="#+id/btnloop"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/btnnext"
android:layout_marginTop="85dp"
android:layout_marginLeft="35dp"
android:background="#drawable/loop_off"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
In above image, you see that you are sending the position of filtered array and sending the songs list (mysongs) which is not filtered. That's why it's happening.
So you need to do is that either send the filtered array. Or add some logic to get the correct position from songs list. that's it.
if you can not figure out then let me know I will update appropriate logic.
If I scroll this list RecycleView with the mouse wheel my items in the list look like unordered.
I do not understand , why?
An incorrect clicked item in the new activity from RecycleView
I have tried to create the separate class CrimeAdapter extends RecyclerView.Adapter<CrimeAdapter.CrimeHolder> and
class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener in the separate file, but I couldn't do it right.
Unfornuntely, I do not have enough experience for this.
I do not know how to write the correct code in the method public void onClick(View v)
Crime.java
package com.bignerdranch.android.criminalintent;
import java.util.Date;
import java.util.UUID;
public class Crime{
private UUID mId;
private String mTitle;
private Date mDate;
private boolean mSolved;
private boolean mRequiresPolice;
public Crime() {
// Generate unique identifier
this(UUID.randomUUID());
}
public Crime(UUID id) {
mId = id;
mDate = new Date();
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public boolean isSolved() {
return mSolved;
}
public void setSolved(boolean solved) {
mSolved = solved;
}
public boolean isRequiresPolice() {
return mRequiresPolice;
}
public void setRequiresPolice(boolean requiresPolice) {
mRequiresPolice = requiresPolice;
}
}
CrimeLab.java
package com.bignerdranch.android.criminalintent;
import android.content.Context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}
return sCrimeLab;
}
private CrimeLab(Context context){
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setTitle("Crime #" + i);
crime.setSolved(i % 2 == 0);
if (i % 4 == 0 ) {crime.setRequiresPolice(true);}
else {crime.setRequiresPolice(false);}
mCrimes.add(crime);
}
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id){
for (Crime crime : mCrimes){
int rez = id.compareTo(crime.getId());
if (crime.getId().equals(id)){
return crime;
}
}
return null;
}
}
CrimeListFragment.java
package com.bignerdranch.android.criminalintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.LayoutRes;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Date;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final int REQUEST_CRIME = 1;
private static final int NOT_REQUIRES_POLICE = 0;
private static final int REQUIRES_POLICE = 1;
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
private Crime mCrime;
private CharSequence mDateFormat;
private int layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container,
false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CrimeHolder(int layout, LayoutInflater inflater, ViewGroup parent ) {
super(inflater.inflate(layout, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
if (itemView.findViewById(R.id.call_police)!=null) {
mButtonCallPolice = (Button) itemView.findViewById(R.id.call_police);
}
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateFormat = DateFormat.format("EEE, MMM dd, yyyy", mCrime.getDate());
mDateTextView.setText(mDateFormat);
mSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE :
View.GONE);
if(mCrime.isRequiresPolice()){
mButtonCallPolice.setEnabled(true);
}
}
#Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(),
CrimeLab.get(requireActivity()).getCrimes().get((getAdapterPosition())).getId());
startActivityForResult(intent, REQUEST_CRIME);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
if (viewType==1) { layout = R.layout.list_item_crime_police;}
else { layout = R.layout.list_item_crime; }
return new CrimeHolder (layout, layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
public int getItemViewType(int position) {
Crime crime = mCrimes.get(position);
return (crime.isRequiresPolice()) ? 1 : 0;
}
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if (mAdapter == null) {
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CRIME) {
// Обработка результата
}
}
public void returnResult() {
getActivity().setResult(Activity.RESULT_OK, null);
}
}
CrimePagerActivity.java
package com.bignerdranch.android.criminalintent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import java.util.List;
import java.util.UUID;
public class CrimePagerActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_ID = "com.bignerdranch.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
MyAdapter mAdapter;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.crime_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
mAdapter = new MyAdapter(getSupportFragmentManager(),mCrimes);
mViewPager.setAdapter(mAdapter);
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
public static class MyAdapter extends FragmentStatePagerAdapter {
private List<Crime> mCrimesCopy;
public MyAdapter(FragmentManager fm, List<Crime> mCrimesParametr) {
//super(fm);
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.mCrimesCopy = mCrimesParametr;
}
#Override
public int getCount() {
return mCrimesCopy.size();
}
#Override
public Fragment getItem(int position) {
Crime crime = mCrimesCopy.get(position);
return CrimeFragment.newInstance(crime.getId());
}
}
}
fragment_crime_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
fragment_crime.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint"
android:inputType=""
android:autofillHints="" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_solved_label"/>
</LinearLayout>
list_item_crime_police.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_title"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_solved" />
<Button
android:id="#+id/call_police"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#string/call_police"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_date" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:contentDescription="#string/todo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved" />
</androidx.constraintlayout.widget.ConstraintLayout>
list_item_crime.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/crime_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_title"
android:textColor="#android:color/black"
android:textSize="18sp"
app:layout_constraintEnd_toStartOf="#+id/crime_solved"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/crime_date"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/crime_solved" />
<ImageView
android:id="#+id/crime_solved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_solved"
android:contentDescription="#string/todo" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_crime_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager.widget.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>
activity_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I think the items in the RecyclerView are unordered because the references for views which are present in your list_item_crime_police.xml or list_item_crime.xml layout file is declared as class members of CrimeListFragment and not inside CrimeHolder class as :
public class CrimeListFragment extends Fragment {
// your other views and variables related declarations
// these are problematic declaration that keeps on being reused
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
// your other declarations
// your other code
}
That's why, the same view instances such as mTitleTextView, mDateTextView, mSolvedImageView, mButtonCallPolice, etc. are being reused for every CrimeHolder instances causing the unordering of the items in the list. Now, in order to fix this problem, you can simply move these lines to code to CrimeHolder class as class variable which would ensures that every new CrimeHolder instance will have separate instances of above-mentioned views as :
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// declare all of them here so there will be unique instances of these views for unique viewholder
private TextView mTitleTextView;
private TextView mDateTextView;
private ImageView mSolvedImageView;
private Button mButtonCallPolice;
public CrimeHolder(int layout, LayoutInflater inflater, ViewGroup parent ) {
View itemView = inflater.inflate(layout, parent, false));
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
mSolvedImageView = (ImageView) itemView.findViewById(R.id.crime_solved);
if (itemView.findViewById(R.id.call_police)!=null) {
mButtonCallPolice = (Button) itemView.findViewById(R.id.call_police);
}
itemView.setOnClickListener(this);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateFormat = DateFormat.format("EEE, MMM dd, yyyy", mCrime.getDate());
mDateTextView.setText(mDateFormat);
mSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE :
View.GONE);
if(mCrime.isRequiresPolice()){
mButtonCallPolice.setEnabled(true);
}
}
#Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(),
CrimeLab.get(requireActivity()).getCrimes().get((getAdapterPosition())).getId());
startActivityForResult(intent, REQUEST_CRIME);
}
}
It fixed my problem and I hope it will fix yours too.
This is the updated code for my RececlerView to show data in my SQLite Database but still I cant make the data to show in my recycler view but there is no errors in my app.
The applications only show "No API Data" which is from this part of my code.
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
I will show you the codes.
This is a part of my DatabaseHelper the method on Listing the data in myDatabase for RecyclerView.
public boolean checkUser(String email) {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry._ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = Timerecordshelper.BeneficiaryEntry.COL_1 + " = ?";
// selection argument
String[] selectionArgs = {email};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'test#gmail.com';
*/
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public List<TimeinData> getAllTimeinData() {
// array of columns to fetch
String[] columns = {
Timerecordshelper.BeneficiaryEntry.COL_1,
Timerecordshelper.BeneficiaryEntry.COL_2,
Timerecordshelper.BeneficiaryEntry.COL_3,
Timerecordshelper.BeneficiaryEntry.COL_4,
Timerecordshelper.BeneficiaryEntry.COL_5,
};
// sorting orders
String sortOrder =
Timerecordshelper.BeneficiaryEntry.COL_1 + " ASC";
List<TimeinData> TimeList = new ArrayList<TimeinData>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Timerecordshelper.BeneficiaryEntry.TABLE_NAME_IN, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TimeinData Timerecords = new TimeinData();
Timerecords.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_1))));
Timerecords.setIn(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_2)));
Timerecords.setCustomer(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_3)));
Timerecords.setBranch(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_4)));
Timerecords.setMachine(cursor.getString(cursor.getColumnIndex(Timerecordshelper.BeneficiaryEntry.COL_5)));
// Adding user record to list
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return TimeList;
}
TimeinRecyclerAdapter.java
package com.example.serviceapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimeinRecyclerAdapter extends
RecyclerView.Adapter<TimeinRecyclerAdapter.BeneficiaryViewHolder> {
private ArrayList<TimeinData> listBeneficiary;
public ImageView overflow;
private Context mContext;
private ArrayList<TimeinData> mFilteredList;
public TimeinRecyclerAdapter(ArrayList<TimeinData> listBeneficiary, Context
mContext) {
this.listBeneficiary = listBeneficiary;
this.mContext = mContext;
this.mFilteredList = listBeneficiary;
}
public class BeneficiaryViewHolder extends RecyclerView.ViewHolder {
public AppCompatTextView textViewName;
public AppCompatTextView textViewEmail;
public AppCompatTextView textViewAddress;
public AppCompatTextView textViewCountry;
public BeneficiaryViewHolder(View view) {
super(view);
textViewName = view.findViewById(R.id.textViewName);
textViewEmail = view.findViewById(R.id.textViewEmail);
textViewAddress = view.findViewById(R.id.textViewAddress);
textViewCountry = view.findViewById(R.id.textViewCountry);
}
}
#Override
public BeneficiaryViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// inflating recycler item view
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_timeinrecycler, parent, false);
return new BeneficiaryViewHolder(itemView);
}
#Override
public void onBindViewHolder(final BeneficiaryViewHolder holder, int
position) {
holder.textViewName.setText(listBeneficiary.get(position).getId());
holder.textViewName.setText(listBeneficiary.get(position).getIn());
holder.textViewEmail.setText(listBeneficiary.get(position).getCustomer());
holder.textViewAddress.setText(listBeneficiary.get(position).getBranch());
holder.textViewCountry.setText(listBeneficiary.get(position).getMachine());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
}
Timerecordshelper.java
package com.example.serviceapplication;
import android.provider.BaseColumns;
public class Timerecordshelper {
public static final class BeneficiaryEntry implements BaseColumns {
public static final String TABLE_NAME_IN = "TABLE_NAME_IN";
public static final String COL_1 = "Job ID";
public static final String COL_2 = "Time In";
public static final String COL_3 = "Customer:";
public static final String COL_4 = "Branch";
public static final String COL_5 = "Machine";
}
}
This codes acts as the gettersetter for my Recycleview to get data in SQLite.
TimeinData.java
package com.example.serviceapplication;
public class TimeinData {
private int id;
private String In;
private String Customer;
private String Branch;
private String Machine;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIn() {
return In;
}
public void setIn(String In) {
this.In = In;
}
public String getCustomer() {
return Customer;
}
public void setCustomer(String Customer) {
this.Customer = Customer;
}
public String getBranch() {
return Branch;
}
public void setBranch(String Branch) {
this.Branch = Branch;
}
public String getMachine() {
return Machine;
}
public void setMachine(String Machine) {
this.Machine = Machine;
}
}
TimerecordsListActivity.java
package com.example.serviceapplication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class TimerecordsListActivty extends AppCompatActivity {
private AppCompatActivity activity = TimerecordsListActivty.this;
Context context = TimerecordsListActivty.this;
private RecyclerView recyclerViewBeneficiary;
private ArrayList<TimeinData> listBeneficiary;
private TimeinRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
SearchView searchBox;
private ArrayList<TimeinData> filteredList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeinrec);
initViews();
initObjects();
Intent intentThatStartedThisActivity = getIntent();
if (intentThatStartedThisActivity.hasExtra("Job ID")) {
//get all needed extras intent
int id = getIntent().getExtras().getInt("ID");
String in = getIntent().getExtras().getString("Time In");
String customer = getIntent().getExtras().getString("Customer");
String branch = getIntent().getExtras().getString("Branch");
String machine = getIntent().getExtras().getString("Machine");
}else{
Toast.makeText(this, "No API Data", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is to initialize views
*/
private void initViews() {
recyclerViewBeneficiary = (RecyclerView)
findViewById(R.id.recyclerViewBeneficiary);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new TimeinRecyclerAdapter(listBeneficiary,
this);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
}
And this is the XML Layouts of my following codes just showing you to understand more about ID i assigned.
Activity_timeinrec.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.serviceapplication.TimerecordsListActivty">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewBeneficiary"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginTop="?actionBarSize"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_timeinrecycler.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/textViewCountry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
I expect that the apps shows all the data in TABLE_NAME_IN, but on the otherhand as I said it only shows the No "API Data".
I have made a ListView in that every ListItem is having EditText ,I want to edit them,But I am not able to edit them,Please help me for that,My code is as below,I have mentioned my java class(activity),Xml and raw file which will be binded to the ListView and adapter:
cart.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/hdr_cart"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/header_bg" />
<TextView
android:id="#+id/tv_title"
style="#style/font_med"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My cart"
android:textColor="#ff0000" />
<ImageView
android:id="#+id/iv_bak"
style="#style/iv_buyingrequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_back" />
</RelativeLayout>
<ListView
android:id="#+id/cart_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/tv_total"
android:layout_below="#+id/hdr_cart" />
<TextView
android:id="#+id/tv_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ll_botom"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:padding="5dp"
android:text="Total:"
android:textSize="20dp" />
<LinearLayout
android:id="#+id/ll_botom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:id="#+id/tv_place_order"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/bg_blu_btn_selector"
android:gravity="center"
android:padding="8dp"
android:text="Place Order"
android:textColor="#ffffff"
android:textSize="16dp"
android:textStyle="bold" />
<Button
android:id="#+id/tv_home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/bg_blu_btn_selector"
android:gravity="center"
android:padding="8dp"
android:text="Continue Shopping"
android:textColor="#ffffff"
android:textSize="16dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
raw.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:padding="10dp" >
<ImageView
android:id="#+id/iv_product_img"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="left"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="product Name"
android:textColor="#545454"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Quantity:"
android:textColor="#000000"
android:textSize="12dp" />
<EditText
android:id="#+id/et_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_qty"
android:background="#drawable/blk_editext"
android:ems="4"
android:gravity="center_vertical"
android:text="200"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/et_qty"
android:text="Acre"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_wholesale_proce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Price:"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_wprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_wholesale_proce"
android:text="100"
android:textColor="#545454"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_retail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_wprice"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Sub Total:"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_rprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_wprice"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_retail"
android:text="100"
android:textColor="#545454"
android:textSize="12dp" />
<TextView
android:id="#+id/pro_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/min_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/fob_price"
android:text=""
android:textColor="#cecece"
android:textSize="12dp" />
</RelativeLayout>
cartList.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
String total, pid;
TextView tv_total;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
tv_total = (TextView) findViewById(R.id.tv_total);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
System.out.println("::::::::::::Long click:::::::::::::::::");
pid = cartList.get(position).get(Const.TAG_PRODUCT_ID);
showCustomeAlert(CartListActivity.this, "Are You Sure want to delete?", "Yehki", "No", "Yes", position, pid);
return false;
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, CartPlaceOrderActivity.class);
startActivity(in);
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
StringBuilder b = new StringBuilder();
for (int i = 0; i > cartContent.getCount(); i++)
b.append(cartContent.getItem(i));
tv_total.setText("Total:" + total);
}
}
public void showCustomeAlert(final Context context, String message, String title, String leftButton, String rightButton, final int position, final String pid2) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup_alert_delete);
dialog.setCancelable(true);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView txt_message = (TextView) dialog.findViewById(R.id.txtMessage);
final Button btn_left = (Button) dialog.findViewById(R.id.btnLeft);
final Button btn_right = (Button) dialog.findViewById(R.id.btnRigth);
TextView txtTitle = (TextView) dialog.findViewById(R.id.txtTitle);
txtTitle.setText(title);
txt_message.setText(message);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
btn_left.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
btn_right.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String pid = cartList.get(position).get(Const.TAG_PRODUCT_ID);
cartList.clear();
new RemoveCart().execute(pid2);
cartContent.notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
/*
* Remove from cart List.........!!!
*/
private class RemoveCart extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_REMOVE_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_id=" + arg0[0];
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
StringBuilder b = new StringBuilder();
for (int i = 0; i > cartContent.getCount(); i++)
b.append(cartContent.getItem(i));
tv_total.setText("Total:" + total);
}
}
}
cartAdapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.ui.WholesaleProductDetailActivity;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class CartAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> cartArray;
private Context mContext;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
String retailPrice;
String wholesalePrice;
String retailQty;
String wholesaleQty;
private ProgressDialog pDialog;
String status;
public CartAdapter(Context paramContext, ArrayList<HashMap<String, String>> cartList) {
this.mContext = paramContext;
this.cartArray = cartList;
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(paramContext));
options = new DisplayImageOptions.Builder().cacheOnDisc(true).showStubImage(R.drawable.logo).showImageOnFail(R.drawable.ic_launcher).build();
}
public int getCount() {
return this.cartArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_cart, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.pid = ((TextView) paramView.findViewById(R.id.pro_id));
localViewholder.proImg = ((ImageView) paramView.findViewById(R.id.iv_product_img));
localViewholder.proName = ((TextView) paramView.findViewById(R.id.product_label));
localViewholder.price = ((TextView) paramView.findViewById(R.id.tv_wprice));
localViewholder.qty = ((EditText) paramView.findViewById(R.id.et_qty));
localViewholder.subTotal = ((TextView) paramView.findViewById(R.id.tv_rprice));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println("::::::::::::::array indexes::::::::::::" + cartArray.get(paramInt));
retailQty = cartArray.get(paramInt).get(Const.TAG_MIN_ORDER_QTY_RETAIL);
retailPrice = cartArray.get(paramInt).get(Const.TAG_RETAIL_PRICE);
wholesaleQty = cartArray.get(paramInt).get(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
wholesalePrice = cartArray.get(paramInt).get(Const.TAG_WHOLESALE_PRICE);
localViewholder.proName.setText(cartArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.pid.setText(cartArray.get(paramInt).get(Const.TAG_PRODUCT_ID));
localViewholder.pid.setVisibility(View.GONE);
localViewholder.qty.setText(cartArray.get(paramInt).get(Const.TAG_QUANTITY));
localViewholder.subTotal.setText(cartArray.get(paramInt).get(Const.TAG_SUBTOTAL));
/*
* for changing the price based on quantity....
*/
localViewholder.price.setText(cartArray.get(paramInt).get(Const.TAG_WHOLESALE_PRICE));
imageLoader.displayImage(cartArray.get(paramInt).get(Const.TAG_PRODUCT_IMG), localViewholder.proImg, options);
return paramView;
}
static class Viewholder {
ImageView proImg;
TextView proName;
TextView price;
TextView subTotal;
TextView pid;
EditText qty;
}
}
Use
myListView.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> listView, View view, int position, long id)
{
EditText yourEditText = (EditText) view.findViewById(R.id.youredittextid);
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
yourEditText.requestFocus();
}
});
The problem is that the selection of the row takes the focus but in order to edit the EditText you need focus on it