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>
Related
I want make some application, it will scanning nearby BLE and sending to server via MQTT. But the scanning proccess to slow. I want to increase the speed of scanning.
mainActivity.java
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
handler.postDelayed(this, 1000);
}
}, 1000);
final Handler handlerStop = new Handler();
handlerStop.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothAdapter.cancelDiscovery();
handlerStop.postDelayed(this, 2000);
}
}, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
bluetoothAdapter.startDiscovery();
}
}
}else {
bluetoothAdapter.cancelDiscovery();
}
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
mqttActivity.java
package com.example.mqtt_active;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MqttActivity extends AppCompatActivity {
private EditText server,port,id;
private Button save;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqtt);
server = findViewById(R.id.serverMQTT);
id = findViewById(R.id.mqttTopic);
port = findViewById(R.id.mqttPort);
save = findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.mqtt_id = id.getText().toString();
MainActivity.mqtt_port = port.getText().toString();
MainActivity.mqtt_server = server.getText().toString();
startActivity(new Intent(MqttActivity.this,MainActivity.class));
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/turnon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.452" />
<Button
android:id="#+id/mqttSet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set MQTT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.511"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/turnon"
app:layout_constraintVertical_bias="0.073" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.524"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mqttSet"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_mqtt.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/serverMQTT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Server"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="MQTT SERVER"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="MQTT TOPIC"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/serverMQTT" />
<EditText
android:id="#+id/mqttTopic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Topic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="MQTT PORT"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mqttTopic" />
<EditText
android:id="#+id/mqttPort"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Port"
app:layout_constraintBottom_toTopOf="#+id/saveButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/textView3"
app:layout_constraintVertical_bias="0.298" />
</androidx.constraintlayout.widget.ConstraintLayout>
How to increase speed of scanning nearby BLE? i expect from this forum, i can increase speed of scanning nearby BLE.
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>
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.
I am currently working with an app that can access an online game to acquire information of my account. I need to use JSON to communicate with the server. I used the following code to try to communicate with the server, but there are no responds from the server. I also noticed that the httpclient and some other popular class were deprecated and I can't find some proper tutorial to teach me on this topic. Any help is appreciated.
activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="deardanielxd.travain2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Username : "
android:id="#+id/Username_Lbl"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:editable="true"
android:minHeight="20dp"
android:layout_alignBottom="#+id/Username_Field"
android:layout_toStartOf="#+id/Username_Field"
android:layout_alignEnd="#+id/Password_Lbl" />
<EditText
android:layout_width="wrap_content"
android:layout_height = "40dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/Username_Field"
android:editable="true"
android:contextClickable="true"
android:textIsSelectable="true"
android:enabled="true"
android:focusable="true"
android:clickable="true"
android:inputType="text"
android:minHeight="40dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/Load_Btn"
android:layout_toEndOf="#+id/Password_Lbl" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Password : "
android:id="#+id/Password_Lbl"
android:layout_below="#+id/Username_Lbl"
android:layout_alignParentStart="true"
android:minHeight="20dp"
android:layout_alignBottom="#+id/Password_Field" />
<EditText
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/Password_Field"
android:password="true"
android:editable="true"
android:textIsSelectable="true"
android:enabled="true"
android:focusable="true"
android:contextClickable="true"
android:clickable="true"
android:inputType="text"
android:minHeight="40dp"
android:layout_below="#+id/Username_Field"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/Username_Field" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="#+id/Load_Btn"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/spinner"
android:layout_below="#+id/Password_Field" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:spinnerMode="dropdown"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/Load_Btn"
android:layout_below="#+id/Password_Lbl" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/SysMsg"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="System : "
android:textColor="#FF0000" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_below="#+id/spinner"
android:layout_alignParentStart="true"
android:layout_above="#+id/SysMsg"
android:layout_alignParentEnd="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/OutPut"
android:enabled="true" />
</ScrollView>
MainActivity.java
package deardanielxd.travain2;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
EditText Username, Password;
Button Load_Btn;
TextView Main_Output;
TextView Sys_Output;
String server = "";
boolean debug = true;
PlayerInfo curr = new PlayerInfo();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetupGadget();
attachListener();
}
private void SetupGadget() {
spinner = (Spinner) findViewById(R.id.spinner);
Username = (EditText) findViewById(R.id.Username_Field);
Password = (EditText) findViewById(R.id.Password_Field);
Load_Btn = (Button) findViewById(R.id.Load_Btn);
Main_Output = (TextView) findViewById(R.id.OutPut);
Sys_Output = (TextView) findViewById(R.id.SysMsg);
ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,Constants.Servers);
spinner.setAdapter(adapter);
}
private void attachListener() {
Load_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (debug) {
MainOutput( "Username : " + Username.getText());
MainOutput( "Password : " + Password.getText());
MainOutput( "Server : " + server);
MainOutput( "Internet Connection : " + (InternetAccess()?"Yes":"No"));
MainOutput( "" );
}
new test(MainActivity.this).execute();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
server = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void SystemOutput(String output) {
Sys_Output.setText("System : " + output);
}
public void MainOutput(String output) {
Main_Output.append("\n" + output);
}
private boolean InternetAccess() {
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
public class test extends AsyncTask<Void, Void, Void>
{
private MainActivity MA;
test(MainActivity ma) {
MA = ma;
}
#Override
protected Void doInBackground(Void... n) {
try {
URL url = new URL("http://"+MA.server+"/api/external.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.connect();
OutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
printout.write(URLEncoder.encode(this.getObj().toString(),"UTF-8").getBytes());
printout.flush ();
printout.close ();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder(in.available());
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
MA.MainOutput(total.toString());
MA.MainOutput("End of Doc");
} finally {
urlConnection.disconnect();
return null;
}
} catch (java.net.MalformedURLException e) {
} catch (java.io.IOException e) {
};
return null;
}
private JSONObject getObj() {
JSONObject jobj = new JSONObject();
try {
jobj.put("email","funckybuggy#gmail.com");
jobj.put("siteName","EasyTravian");
jobj.put("sitUrl","testing.com");
jobj.put("public",false);
} catch (org.json.JSONException e) {
}
return jobj;
}
}
public PlayerInfo getCurrentPlayerInfo() {
return this.curr;
}
public void UpdateCurr() {
this.curr.Username = this.Username.getText().toString();
this.curr.Password = this.Password.getText().toString();
this.curr.Server = this.server;
}
}
Constants.java
public class Constants {
public static final String[] Servers = {
"ts1.travian.hk",
"ts2.travian.hk",
"ts20.travian.hk",
"tx3.travian.hk",
"ts4.travian.hk",
"ts19.travian.hk",
"ts3.travian.hk",
"ts6.travian.hk",
"ts5.travian.hk"
};
}
I don't think you should encode the body of the message.
The reason it is called "URLEncoder" is because it is used to encode a URL but this is the body of your message.
Also, the internal try block you have is redundant and also you should change the request method to GET in the middle of the request.
There's no need to flush the bytes.
Remember that with a POST request, nothing is sent until you read the response using your InputStream.
You should use Volley Library for it.
It's very good for the Rest API's.
And managing server calls is simple with it.
Add the library by compiling
compile 'com.android.volley:volley:1.0.0'
then make a Singleton class to handle all the volley requests.
Volley provides JsonArrayRequest and JsonObjectRequest which are very helpful during network calls.
Here is volley singleton class
public class MyApplication extends Application
{
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance()
{
return mInstance;
}
public RequestQueue getReqQueue()
{
if (mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToReqQueue(Request<T> req, String tag)
{
getReqQueue().add(req);
}
public <T> void addToReqQueue(Request<T> req)
{
getReqQueue().add(req);
}
public void cancelPendingReq(Object tag)
{
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Add this to your application tag in manifest
<application
android:name="MyApplication">
This is a sample JsonObjectRequest
JsonObjectRequest request = new JsonObjectRequest("requestMethod","url","input_data",
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
}
});
MyApplication.getInstance().addToReqQueue(request);
Am using the following code. Every time on logcat am getting the dialogue ad is not visible. not refreshing. And the ad is not showing but the same thing is working fine when am using it with out the help of a fragments.
Somebody please tell me whats worng with my code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="4"
android:gravity="center"
>
<TextView
android:id="#+id/textView1"
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<Button
android:id="#+id/Button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:paddingRight="5dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#android:color/transparent"
/>
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="250dp"
/>
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="10dp"
android:text=""
/>
<TextView
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="10dp"
/>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxx" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
java code
package com.xx.xx;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONObject;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class DetailsFragment extends Fragment {
public DetailsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
return rootView;
}
ListView list;
Lazyimg adapter;
String name,imageurl,description,ingradiants,tduration;
String[] mname,mimageurl;
private ProgressDialog dialog;
String ids,b1status;
Button b1;
private static Typeface typeFace = null;
private static Typeface itypeFace = null;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AdView adView = (AdView) getActivity().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
b1=(Button)getActivity().findViewById(R.id.Button1);
ids= getArguments().getString("ids");
ids=ids.replace(" ", "%20");
ids=ids.replace("-", "%27");
initTypeFace(getActivity());
iinitTypeFace(getActivity());
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
GetData obj = new GetData();
dialog = ProgressDialog.show(getActivity(), "",
"Please wait...", true);
TelephonyManager tManager = (TelephonyManager) getActivity().getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceIMEI = tManager.getDeviceId();
String urls="cczczccxx/xxy.php?id="+ids+"&imei="+deviceIMEI+"&fav=jomin";
obj.execute(urls);
}
});
loadingPopup();
}
private void loadingPopup() {
GetData obj = new GetData();
dialog = ProgressDialog.show(getActivity(), "",
"Loading recipe details...", true);
TelephonyManager tManager = (TelephonyManager) getActivity().getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceIMEI = tManager.getDeviceId();
String urls="xxx/xxy.php?id="+ids+"&imei="+deviceIMEI;
obj.execute(urls);
}
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
data = buffer.toString();
JSONObject fulldata = new JSONObject(data);
JSONArray albumdata = (JSONArray) fulldata.get("data");
JSONObject sobj = null;
name=""; imageurl=""; description=""; ingradiants=""; tduration=""; b1status="";
for(int j=0;j<albumdata.length();++j)
{
sobj= (JSONObject) albumdata.get(j);
b1status += (String)sobj.get("fav");
name += (String) sobj.get("name");
imageurl += (String) sobj.get("imageurl");
description += (String) sobj.get("description");
ingradiants += (String) sobj.get("ingradiants");
tduration += (String) sobj.get("tduration");
}
return "";
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
catch(Exception e)
{
//
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
dialog.dismiss();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e);
}
if(result==null)
{
new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("\n Connection Error..!\n")
.setPositiveButton("Exit", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
})
.setNegativeButton("Retry", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialoga, int which) {
try {
dialog.dismiss();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e);
}
GetData obj = new GetData();
dialog = ProgressDialog.show(getActivity(), "",
"Loading recipe details...", true);
TelephonyManager tManager = (TelephonyManager) getActivity().getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String deviceIMEI = tManager.getDeviceId();
String urls="xxxxy.php?id="+ids+"&imei="+deviceIMEI;
obj.execute(urls);
}
})
.show();
}
else
{
mname = name.split("xstream");
mimageurl = imageurl.split("xstream");
if(b1status.equals(""))
{
b1.setBackgroundResource(R.drawable.favr);
}
else if(b1status.equals("f"))
{
b1.setBackgroundResource(R.drawable.favrg);
}
TextView ting=(TextView)getView().findViewById(R.id.textView4);
ting.setText("Ingredients");
ting.setTypeface(typeFace);
ting.setTextColor(Color.parseColor("#210B61"));
ting.setTextSize(25);
TextView tpre=(TextView)getView().findViewById(R.id.textView5);
tpre.setText("\n\nDirections for Preparation");
tpre.setTypeface(typeFace);
tpre.setTextColor(Color.parseColor("#210B61"));
tpre.setTextSize(25);
if(tduration.equals(""))
{
TextView ttduration=(TextView)getView().findViewById(R.id.textView1);
ttduration.setText("READY IN : Depends");
ttduration.setTypeface(itypeFace);
ttduration.setTextColor(Color.parseColor("#FF8000"));
ttduration.setTextSize(20);
}
else
{
TextView ttduration=(TextView)getView().findViewById(R.id.textView1);
ttduration.setText("READY IN : "+tduration);
ttduration.setTypeface(itypeFace);
ttduration.setTextColor(Color.parseColor("#FF8000"));
ttduration.setTextSize(20);
}
TextView tingradiants=(TextView)getView().findViewById(R.id.textView2);
ingradiants=ingradiants.replaceAll("<br>", "\n\n");
ingradiants=ingradiants.replaceAll(""", "\"");
ingradiants=ingradiants.replaceAll("'", "'");
ingradiants=ingradiants.replaceAll("®", " ");
tingradiants.setText(ingradiants);
tingradiants.setTypeface(typeFace);
tingradiants.setTextColor(Color.parseColor("#000000"));
tingradiants.setTextSize(20);
TextView tdescription=(TextView)getView().findViewById(R.id.textView3);
description=description.replaceAll("<br>", "\n\n");
description=description.replaceAll(""", "\"");
description=description.replaceAll("'", "'");
description=description.replaceAll("®", " ");
tdescription.setText(description);
tdescription.setTypeface(itypeFace);
tdescription.setTextSize(20);
list=(ListView)getView().findViewById(R.id.list);
// Create custom adapter for listview
adapter=new Lazyimg(getActivity(), mimageurl,mname);
//Set adapter to listview
list.setAdapter(adapter);
}
//Button b=(Button)findViewById(R.id.button1);
//b.setOnClickListener(listener);
}
}
public static void initTypeFace(Context context) {
try {
typeFace = Typeface.createFromAsset(context.getAssets(), "Nexa_Light.otf");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void iinitTypeFace(Context context) {
try {
itypeFace = Typeface.createFromAsset(context.getAssets(), "iowan.ttf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
It could be as simple as your AdView not actually being on screen. The AdView is contained within a ScrollView so there is no guarantee that it is actually on screen.
You have a complicated view hierarchy. Suggest you simplify it and move the AdView outside of your ScrollView.