When i click the login button to process and check my codes it closes the whole app..
logcat error
08-30 00:48:33.876 20672-20672/com.map.laurence.crms2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.map.laurence.crms2, PID: 20672
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.map.laurence.crms2.BackgroundWorker.onPostExecute(BackgroundWorker.java:80)
at com.map.laurence.crms2.BackgroundWorker.onPostExecute(BackgroundWorker.java:22)
at android.os.AsyncTask.finish(AsyncTask.java:692)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:709)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
this class is my problem
BackgroundWorker.java
package com.map.laurence.crms2;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.map.laurence.crms2.Menu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.8.101/AndroidDB/login.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("user_pass","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("login success")) {
context.startActivity(new Intent(context, Menu.class));
}else{
alertDialog.setMessage(result);
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
login.java
package com.map.laurence.crms2;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
public EditText user,pass;
static Login login;
private static final String TAG = "Login";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
login = this;
user = (EditText) findViewById(R.id.etUser);
pass = (EditText) findViewById(R.id.etPass);
}
public static Login getInstance(){
return login;
}
public void onLogin(View v){
String username = user.getText().toString();
String password = pass.getText().toString();
if(username == null || username.equals("") || password == null || password.equals("")) {
Toast.makeText(this,"Empty Fields!",Toast.LENGTH_LONG).show();
}else
{
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
}
#Override
public void onBackPressed() {
Log.d("back button", "back button pressed");
AlertDialog.Builder ad1=new AlertDialog.Builder(Login.this);
ad1.setMessage("Are you sure you want to Exit? ");
ad1.setCancelable(false);
ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AlertDialog alert=ad1.create();
alert.show();
}
}
ive tried clicking the button for toast message and it doesnt crashes.
ive tried replacing this
super.onPostExecute(result);
if(result.equals("login success")) {
context.startActivity(new Intent(context, Menu.class));
}else{
alertDialog.setMessage(result);
alertDialog.show();
}
with this
super.onPostExecute(result);
if(result.equals("login success")) {
alertDialog.setMessage(result);
alertDialog.show();
}else{
alertDialog.setMessage(result);
alertDialog.show();
}
but it gave me the "login Status" from here
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
and no dialog response from the server please help me thanks
here is the login.xml file for those who wanna try it out
<?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"
android:orientation="vertical"
android:background="#drawable/backg"
tools:context="com.map.laurence.crms2.Login">
<LinearLayout
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top|center"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:layout_centerInParent="true"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/title"
app:srcCompat="#drawable/logoo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:gravity="center"
android:text="Apalit Portable" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:gravity="center"
android:text="Census Application" />
</LinearLayout>
<LinearLayout
android:layout_width="292dp"
android:layout_height="265dp"
android:baselineAligned="false"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:layout_below="#+id/title"
android:layout_centerInParent="true"
>
<EditText
android:id="#+id/etUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/text_edge"
android:ems="10"
android:hint="#string/username"
android:inputType="textPersonName"
android:textAlignment="viewStart"
android:textSize="25sp" />
<EditText
android:id="#+id/etPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:background="#drawable/text_edge"
android:ems="10"
android:hint="#string/password"
android:inputType="textPassword"
android:textAlignment="viewStart"
android:textSize="25sp" />
<Button
android:id="#+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/login"
android:textColor="#fff"
android:layout_marginTop="50dp"
android:onClick="onLogin"
android:background="#drawable/button_file"
android:textAlignment="center"
/>
</LinearLayout>
</RelativeLayout>
every help will much be appreciated thanks
Related
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 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.
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);
I'm going to create a simple register form app that when user insert their username and password, EditText in UI shows the id of their record in database.
My app insert users into database correctly and show JSON output into EditText.
For Example when I insert first user to my database, EditText show this:
{
"id": "1", "0":"1"
}
But, I want show this in EditText:
1 instead of
{
"id" : "1", "0" : "1"
}
activity_main.xml
<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:background="#00aeef"
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=".MainActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="18dp"
android:text="Register Example"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="Username:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_username"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/edt_result"
android:layout_below="#+id/edt_password"
android:layout_marginTop="16dp"
android:background="#ffffff"
android:text="Insert"
android:textColor="#00aeef" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/edt_username"
android:text="Password:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_password"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignLeft="#+id/edt_username"
android:layout_below="#+id/textView2"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
<EditText
android:id="#+id/edt_result"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/btn_insert"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
</RelativeLayout>
InsertClass.java
package com.example.testphp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class InsertClass extends AsyncTask<String, Void, String>{
private Context context;
private ProgressDialog pDialog;
private EditText edt;
private String json = "";
private JSONObject jObj = null;
public InsertClass(Context context, EditText edt)
{
this.context = context;
pDialog = new ProgressDialog(context);
this.edt = edt;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading... Please wait");
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
try
{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://10.0.2.2:8020/test/test.php";
String data = URLEncoder.encode("username","utf-8") +
"=" + URLEncoder.encode(username,"utf-8");
data += "&" + URLEncoder.encode("password","utf-8") +
"=" + URLEncoder.encode(password,"utf-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
json = sb.toString();
jObj = new JSONObject(json);
return sb.toString();
}
catch(JSONExeption e)
{
return new String("Exeption: " + e.getMessage());
}
catch(Exception e)
{
return new String("Exeption: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
try
{
edt.setText(jObj.getString("id"));
}
catch (JSONExeption e)
{ e.printStackTrace(); }
}
}
MainActivity.java
package com.example.testphp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
String username;
String password;
EditText edtUsername;
EditText edtPassword;
EditText edtResult;
Button btnInsert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsert = (Button) findViewById(R.id.btn_insert);
edtPassword = (EditText) findViewById(R.id.edt_password);
edtUsername = (EditText) findViewById(R.id.edt_username);
edtResult = (EditText) findViewById(R.id.edt_result);
btnInsert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = edtUsername.getText().toString();
password = edtPassword.getText().toString();
new InsertClass(MainActivity.this, edtResult).execute(username,password);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
test.PHP
<?php
$con = mysqli_connect("localhost" , "root" , "","test");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES '$username','$password')") or die(mysqli_query($con));
if($result)
{
$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = '$username'") or die(mysqli_query($con));
if($id_result)
{
$id_result = mysqli_fetch_array($id_result);
$response = array("id" => $id_result);
echo json_encode($response);
}
}
mysqli_close($con);
?>
Any suggestion, would be appreciated ...
Your response from PHP for user id=17 is {"id":{"0":"17","id":"17"}}
Try to change in php script
//$response = array("id" => $id_result);
$response["id"] = $id_result["id"];
then your rsponse will be {"id":"17"}
In your class InsertClass and function doInBackground() where you are converting result string to JsonObject like
json = sb.toString();
jObj = new JSONObject(json);
Add code:
String result = jObj.getString ("id");
Return result;
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.