Google map marking to fill address automatically using marker - java

I want to mark my Address(Edit Text) with google map marking.
I have created a simple form but i want to mark it on map when i fill the address and drop a marker on the same place.
I am getting the latitude and longitude for address field then i would pin it using a marker but i have issues at the initial stage only(please consider me as a noob in android since i have started few days back)
SignUp Activity
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowCloseListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import butterknife.Bind;
import butterknife.ButterKnife;
public class SignupActivity extends FragmentActivity implements OnMarkerClickListener, OnMarkerDragListener, OnInfoWindowClickListener, OnMapReadyCallback, OnInfoWindowCloseListener, GoogleMap.OnInfoWindowLongClickListener, OnSeekBarChangeListener {
private static final String TAG = "SignupActivity";
private GoogleMap googleMap;
private static LatLng goodLatLng = new LatLng(37, -120);
LatLng addressPos;
Marker addressMarker;
#Bind(R.id.input_name)
EditText _nameText;
#Bind(R.id.input_address)
EditText _addressText;
#Bind(R.id.input_email)
EditText _emailText;
#Bind(R.id.input_mobile)
EditText _mobileText;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.input_reEnterPassword)
EditText _reEnterPasswordText;
#Bind(R.id.btn_signup)
Button _signupButton;
#Bind(R.id.link_login)
TextView _loginLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
String address = _addressText.getText().toString();
// Initial Map
try {
if (googleMap == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void signup() {
Log.d(TAG, "Signup");
if (!validate()) {
onSignupFailed();
return;
}
_signupButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account...");
progressDialog.show();
String name = _nameText.getText().toString();
String address = _addressText.getText().toString();
String email = _emailText.getText().toString();
String mobile = _mobileText.getText().toString();
String password = _passwordText.getText().toString();
String reEnterPassword = _reEnterPasswordText.getText().toString();
// TODO: Implement your own signup logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onSignupSuccess or onSignupFailed
// depending on success
onSignupSuccess();
// onSignupFailed();
progressDialog.dismiss();
}
}, 3000);
}
public void onSignupSuccess() {
_signupButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = _nameText.getText().toString();
String address = _addressText.getText().toString();
String email = _emailText.getText().toString();
String mobile = _mobileText.getText().toString();
String password = _passwordText.getText().toString();
String reEnterPassword = _reEnterPasswordText.getText().toString();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (address.isEmpty()) {
_addressText.setError("Enter Valid Address");
valid = false;
} else {
_addressText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (mobile.isEmpty() || mobile.length()!=10) {
_mobileText.setError("Enter Valid Mobile Number");
valid = false;
} else {
_mobileText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
if (reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))) {
_reEnterPasswordText.setError("Password Do not match");
valid = false;
} else {
_reEnterPasswordText.setError(null);
}
return valid;
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
public void onInfoWindowClick(Marker marker) {
}
#Override
public void onMapReady(GoogleMap Map) {
googleMap=Map;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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;
}
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Address"));
}
public void showAddressMarker(View view) {
String newAddress = _addressText.getText().toString();
if (newAddress != null) {
new PlaceAMarker().execute(newAddress);
}
}
class PlaceAMarker extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String startAddress = params[0];
startAddress = startAddress.replaceAll(" ", "%20");
getLatLng(startAddress, false);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
addressMarker = googleMap.addMarker(new MarkerOptions()
.position(addressPos).title("Address"));
}
}
protected void getLatLng(String address, boolean setDestination) {
String uri = "http://maps.google.com/maps/api/geocode/json?address="
+ address + "&sensor=false";
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int byteData;
while ((byteData = stream.read()) != -1) {
stringBuilder.append((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
double lat = 0.0, lng = 0.0;
JSONObject jsonObject;
try {
jsonObject = new JSONObject(stringBuilder.toString());
lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}
addressPos = new LatLng(lat, lng);
}
#Override
public void onInfoWindowClose(Marker marker) {
}
#Override
public void onInfoWindowLongClick(Marker marker) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
Main Activity file
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.GoogleMap;
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
signup xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" />
<!-- Name Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_name"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<!-- Address Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<fragment
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment" />
<EditText android:id="#+id/input_address"
style="#style/TextLabel"
android:layout_marginTop="23dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:ems="10"
android:layout_below="#+id/map"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:hint="Address" />
</android.support.design.widget.TextInputLayout>
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_email"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<!-- mobile number -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_mobile"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_password"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Password Re-enter Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_reEnterPassword"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Re-enter Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Create Account"/>
<TextView android:id="#+id/link_login"
style="#style/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Already a member? Login"
android:gravity="center"
android:textSize="16dip"/>
</LinearLayout>
</ScrollView>
This is the error which i get at runtime nad please specify the thing clearly since i am new to android and keen to learn fast.
Error Log
AndroidRuntime: FATAL EXCEPTION: main Process: package, PID: 6547 java.lang.RuntimeException: Unable to start activity ComponentInfo{package.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2519) at android.app.ActivityThread.access$800(ActivityThread.java:162) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:189) at android.app.ActivityThread.main(ActivityThread.java:5532) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment and so on.

Related

Send data from Android to ESP32 with Bluetooth

I've searched many tutorials on stackoverflow but can't understand anything and no one has a similar code as me.
I just want to send an "a" when i click the OFF button and "A" when i click the "ON" button. I used the OutputStream.write method but it is not working.
Here is my code:
jetControl.java
package com.example.btjetski;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
public class jetControl extends AppCompatActivity {
Button buttonON1, buttonOFF1;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private final boolean isBtConnected = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jet_control);
Intent intent = getIntent();
address = intent.getStringExtra(Peripherique.EXTRA_ADDRESS); //recevoir l'adresse du périphérique BT
}
private void setOnClickListener() {
buttonON1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TurnOnJetski1();
}
});
buttonOFF1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TurnOffJetski1();
}
});
}
private void TurnOnJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("A".getBytes());
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
}
private void TurnOffJetski1() {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("a".getBytes());
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
}
private void Disconnect() {
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e) {
Toast.makeText(this, "Erreur", Toast.LENGTH_LONG);
}
}
finish();
}
}
activity_jet_control.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=".jetControl">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="4dp"
android:layout_marginTop="8dp"
android:text="Contrôle de JETSKI"
android:textSize="24dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="47dp"
android:layout_marginTop="95dp"
android:text="Jetski 1"
android:textSize="18sp" />
<Button
android:id="#+id/buttonON1"
android:layout_width="81dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="129dp"
android:backgroundTint="#12730C"
android:text="ON" />
<Button
android:id="#+id/buttonOFF1"
android:layout_width="77dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="86dp"
android:layout_marginTop="129dp"
android:backgroundTint="#FF0000"
android:text="OFF" />
</RelativeLayout>

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>

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.

Google map marking with address field

I want to mark my Address(Edit Text) with google map marking.
I have created a simple form but i want to mark it on map when i fill the address and drop a marker on the same place.
I am getting the latitude and longitude for address field then i would pin it using a marker but i have issues at the initial stage only(please consider me as a noob in android since i have started few days back)
SignUp Activity
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowCloseListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import butterknife.Bind;
import butterknife.ButterKnife;
public class SignupActivity extends FragmentActivity implements OnMarkerClickListener, OnMarkerDragListener, OnInfoWindowClickListener, OnMapReadyCallback, OnInfoWindowCloseListener, GoogleMap.OnInfoWindowLongClickListener, OnSeekBarChangeListener {
private static final String TAG = "SignupActivity";
private GoogleMap googleMap;
private static LatLng goodLatLng = new LatLng(37, -120);
LatLng addressPos;
Marker addressMarker;
#Bind(R.id.input_name)
EditText _nameText;
#Bind(R.id.input_address)
EditText _addressText;
#Bind(R.id.input_email)
EditText _emailText;
#Bind(R.id.input_mobile)
EditText _mobileText;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.input_reEnterPassword)
EditText _reEnterPasswordText;
#Bind(R.id.btn_signup)
Button _signupButton;
#Bind(R.id.link_login)
TextView _loginLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
String address = _addressText.getText().toString();
// Initial Map
try {
if (googleMap == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void signup() {
Log.d(TAG, "Signup");
if (!validate()) {
onSignupFailed();
return;
}
_signupButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account...");
progressDialog.show();
String name = _nameText.getText().toString();
String address = _addressText.getText().toString();
String email = _emailText.getText().toString();
String mobile = _mobileText.getText().toString();
String password = _passwordText.getText().toString();
String reEnterPassword = _reEnterPasswordText.getText().toString();
// TODO: Implement your own signup logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onSignupSuccess or onSignupFailed
// depending on success
onSignupSuccess();
// onSignupFailed();
progressDialog.dismiss();
}
}, 3000);
}
public void onSignupSuccess() {
_signupButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = _nameText.getText().toString();
String address = _addressText.getText().toString();
String email = _emailText.getText().toString();
String mobile = _mobileText.getText().toString();
String password = _passwordText.getText().toString();
String reEnterPassword = _reEnterPasswordText.getText().toString();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (address.isEmpty()) {
_addressText.setError("Enter Valid Address");
valid = false;
} else {
_addressText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (mobile.isEmpty() || mobile.length()!=10) {
_mobileText.setError("Enter Valid Mobile Number");
valid = false;
} else {
_mobileText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
if (reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))) {
_reEnterPasswordText.setError("Password Do not match");
valid = false;
} else {
_reEnterPasswordText.setError(null);
}
return valid;
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
public void onInfoWindowClick(Marker marker) {
}
#Override
public void onMapReady(GoogleMap Map) {
googleMap=Map;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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;
}
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Address"));
}
public void showAddressMarker(View view) {
String newAddress = _addressText.getText().toString();
if (newAddress != null) {
new PlaceAMarker().execute(newAddress);
}
}
class PlaceAMarker extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String startAddress = params[0];
startAddress = startAddress.replaceAll(" ", "%20");
getLatLng(startAddress, false);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
addressMarker = googleMap.addMarker(new MarkerOptions()
.position(addressPos).title("Address"));
}
}
protected void getLatLng(String address, boolean setDestination) {
String uri = "http://maps.google.com/maps/api/geocode/json?address="
+ address + "&sensor=false";
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int byteData;
while ((byteData = stream.read()) != -1) {
stringBuilder.append((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
double lat = 0.0, lng = 0.0;
JSONObject jsonObject;
try {
jsonObject = new JSONObject(stringBuilder.toString());
lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}
addressPos = new LatLng(lat, lng);
}
#Override
public void onInfoWindowClose(Marker marker) {
}
#Override
public void onInfoWindowLongClick(Marker marker) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
Main Activity file
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.GoogleMap;
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
signup xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" />
<!-- Name Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_name"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<!-- Address Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<fragment
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment" />
<EditText android:id="#+id/input_address"
style="#style/TextLabel"
android:layout_marginTop="23dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:ems="10"
android:layout_below="#+id/map"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:hint="Address" />
</android.support.design.widget.TextInputLayout>
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_email"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<!-- mobile number -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_mobile"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_password"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Password Re-enter Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_reEnterPassword"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Re-enter Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Create Account"/>
<TextView android:id="#+id/link_login"
style="#style/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Already a member? Login"
android:gravity="center"
android:textSize="16dip"/>
</LinearLayout>
</ScrollView>
AndroidRuntime: FATAL EXCEPTION: main
Process: package, PID: 6547
java.lang.RuntimeException: Unable to start activity ComponentInfo{package.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2519)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5532)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
addMarker(latLng);
}
});
private void addMarker(LatLng latLng){
String text=editText.getText().toString();
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(text));
}
Simple method . do your customization
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" />
<!-- Name Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_name"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<fragment
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment" />
<!-- Address Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_address"
style="#style/TextLabel"
android:layout_marginTop="23dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:ems="10"
android:layout_below="#+id/map"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:hint="Address" />
</android.support.design.widget.TextInputLayout>
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_email"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<!-- mobile number -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_mobile"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_password"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Password Re-enter Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_reEnterPassword"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Re-enter Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Create Account"/>
<TextView android:id="#+id/link_login"
style="#style/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Already a member? Login"
android:gravity="center"
android:textSize="16dip"/>
</LinearLayout>
</ScrollView>
please change the xml code and try

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

Categories