How can I create custom TextToSpeech audio files on buttonclick? - java

With this code i want to create custom TextToSpeech files with the text written in the Textedit.
The User can write something in the TextEdit and the TextToSpeech converts this into speech and then I want to create this speech as a audiofile, which I can share.
But now I dont know where my error is and I don't know further.
Could you please help me :)
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import static de.fresenborg.aufeinwort4.R.id.editText;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener, View.OnClickListener {
private TextToSpeech tts;
private static String fileLocation;
private static String text;
public TextToSpeechFile(String fLocation, String txt) {
fileLocation = fLocation;
text = txt;
}
#Override
public void onClick(View view) {
final EditText wassoll = (EditText) findViewById(editText);
tts.speak(wassoll.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
ImageButton Sharebutton = (ImageButton) findViewById(R.id.Sharebutton);
Sharebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
public static void createFile(){
TextToSpeech tts;
HashMap<String, String> myHashRender = new HashMap();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, myHashRender, fileLocation);
final int utteranceId = 1;
File destinationFile = new File(getCacheDir(), utteranceId + ".wav");
int utteranceId++;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.synthesizeToFile(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED, null, destinationFile, utteranceId);
} else {
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
tts.synthesizeToFile(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED, params, destinationFile.getPath());)
tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String s) {
if (s.equals(utteranceId)) {
}
}
});
}
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int arg0) {
tts.setLanguage(Locale.GERMAN);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
}
This is my XML:
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/my_toolbar"
android:ems="10"
android:hint="Was soll ich sagen?"
android:inputType="textMultiLine"
android:lines="8"
android:minLines="1"
android:text="#string/wassoll" />
<ImageButton
android:id="#+id/Sharebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button"
android:layout_toEndOf="#+id/button"
android:layout_toRightOf="#+id/button"
android:background="#null"
app:srcCompat="#drawable/share" />
<Button
android:id="#+id/button"
android:layout_width="130dp"
android:layout_height="50dp"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="#string/button_sag_es" />

Related

I am making OCR Reader Application. When I create the PDF of generated text, it is not saved as I want. There is one problem in the while loop

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 in translation display in translation app on android studio

Hello eveyone i hope you are all doing good. I have a little problem and I couldn't find the solution. I have a translation app and after the user input his phrase by a record, the translation message doesn't appear. So I hope that someone could help me.
Here is my xml file:
<?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">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:id="#+id/idBtnTranslateLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TransledText"
android:layout_centerInParent="true"
android:text="Translate language" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:layout_marginTop="128dp"
android:background="#color/white"
android:padding="40dp"
android:src="#drawable/ic_baseline_mic_24" />
<TextView
android:id="#+id/TransledText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edittext"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:gravity="center_horizontal"
android:text="Translated language"
android:textAlignment="center"
android:textSize="20sp"
tools:ignore="UnknownId" />
</RelativeLayout>
And my main code:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;
public class MainActivity extends AppCompatActivity {
private static final int CodeSpeechInput =100;
private TextView EditText;
private ImageButton SpeakButton;
private TextView TransledText;
FirebaseTranslator englishFrenshTranslator;
private Button translateLanguageBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseTranslatorOptions options =
new FirebaseTranslatorOptions.Builder()
.setSourceLanguage(FirebaseTranslateLanguage.EN)
.setTargetLanguage(FirebaseTranslateLanguage.FR)
.build();
englishFrenshTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options);
EditText = (TextView) findViewById(R.id.edittext);
SpeakButton = (ImageButton) findViewById(R.id.button);
TransledText = (TextView) findViewById(R.id.TransledText);
translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage);
translateLanguageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = EditText.getText().toString();
downloadModal(string);
}
private void downloadModal(String input) {
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build();
englishFrenshTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// this method is called when modal is downloaded successfully.
Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show();
// calling method to translate our entered text.
translateLanguage(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show();
}
});
}
private void translateLanguage(String input) {
englishFrenshTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String result) {
TransledText.setText(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show();
}
});
}
});
SpeakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
try {
startActivityForResult(intent, CodeSpeechInput);
} catch (ActivityNotFoundException a) {
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CodeSpeechInput : {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
EditText.setText(result.get(0));
}
break;
}
}
}
}
I also use firebase if that could help you.

Search filter on list view returns wrong result on clicking

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.

Editext inside ListItem not editable in android

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

textview into an SMS body Android

I am making an application for Android where it displays your exact coordinates via GPS in a text view when you open the app. You then press a button, and an SMS is sent to a preset number with your coordinates. I have everything working, but the SMS body. I can't figure out how to take the textview with your coordinates and have it send in the SMS body. Any help would be awesome!
MAIN JAVA PAGE
package com.example.test;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, this);
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
String messageToSend = "R.id.textview1";
String number = "8143664050";
SmsManager.getDefault().sendTextMessage(number, null, messageToSend, null,null);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS failed!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
XML FILE
<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" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textview1"
android:layout_marginRight="16dp"
android:layout_marginTop="22dp"
android:onClick="gotoActivity"
android:text="Button" />
</RelativeLayout>
Try to change this:
String messageToSend = "R.id.textview1";
to this
TextView tv = (TextView) findViewById(R.id.textview1);
String messageToSend = tv.getText().toString();

Categories