Why do images take so long to load in this app? - java

I just started making an app using Google Places API. So far the app lets the user select a place and then it displays an image of the place. However, the image takes minutes to load and sometimes doesn't load at all. Please let me know if you see the error.
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private int PLACE_PICKER_REQUEST = 1;
private TextView tvName;
private TextView tvAddress;
private TextView tvAttributions;
private TextView price;
private TextView phone;
private TextView rating;
TextView id;
ImageView downloadedImg;
CharSequence placeID;
String photoReference;
public void logStuff (){
//
ImageDownloader task = new ImageDownloader();
Bitmap myImage;
try {
myImage = task.execute("https://maps.googleapis.com/maps/api/place/photo?maxwidth=500&maxheight=500&photoreference=" + photoReference + "&key=APIKEY").get();
downloadedImg.setImageBitmap(myImage);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.i("button", "tapped");
Log.i("imageurl", (String) placeID);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvName = (TextView) findViewById(R.id.name);
tvAddress = (TextView) findViewById(R.id.address);
tvAttributions = (TextView) findViewById(R.id.attributions);
price = (TextView) findViewById(R.id.price);
phone = (TextView) findViewById(R.id.phone);
rating = (TextView) findViewById(R.id.rating);
id = (TextView) findViewById(R.id.placeId);
downloadedImg = (ImageView) findViewById(R.id.imageView);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
}
public void onPickButtonClick(View v) {
// Construct an intent for the place picker
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(this);
// Start the intent by requesting a result,
// identified by a request code.
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
// The user has selected a place. Extract the name and address.
final Place place = PlacePicker.getPlace(data, this);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
final int priceLevel = place.getPriceLevel();
final CharSequence phoneNum = place.getPhoneNumber();
final float rate = place.getRating();
placeID = place.getId();
logStuff();
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID + "&key=APIKEY").get();
Pattern p = Pattern.compile("photo_reference\" : \"(.*?)\"");
Matcher m = p.matcher(result);
while (m.find()) {
photoReference = m.group(1);
Log.i("PLACE", photoReference);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.i("Contents Of URL", result);
String attributions = PlacePicker.getAttributions(data);
if (attributions == null) {
attributions = "";
}
tvName.setText(name);
tvAddress.setText(address);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
ImageDownloader.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DownloadTask.java
import android.os.AsyncTask;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch(Exception e) {
e.printStackTrace();
return "Failed";
}
}
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"
tools:context=".PlacePickerActivity">
<!--including the toobar-->
<include layout="#layout/toolbar" />
<TextView
android:id="#+id/name"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/attributions"
android:layout_alignEnd="#+id/attributions"
android:layout_below="#+id/toolbar"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/name"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/attributions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="attributions"/>
<Button
android:layout_width="350dp"
android:layout_height="75dp"
android:onClick="onPickButtonClick"
android:text="Find a location"
android:id="#+id/button"
android:textSize="30dp"
android:background="#ebb70d"
android:layout_above="#+id/attributions"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Rating:"
android:id="#+id/rating"
android:layout_alignBaseline="#+id/phone"
android:layout_alignBottom="#+id/phone"
android:layout_alignStart="#+id/phone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Phone"
android:id="#+id/phone"
android:layout_below="#+id/address"
android:layout_centerHorizontal="true"
android:layout_marginTop="94dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:id="#+id/price"
android:layout_below="#+id/phone"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="place Id"
android:id="#+id/placeId"
android:layout_below="#+id/price"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
<ImageView
android:layout_width="500dp"
android:layout_height="500dp"
android:id="#+id/imageView"
android:layout_above="#+id/rating"
android:layout_alignTop="#+id/name"
android:layout_alignStart="#+id/button"
android:layout_alignEnd="#+id/button"
android:maxHeight="500dp"
android:maxWidth="500dp" />
</RelativeLayout>
NOTE: If you wish to test this, you will need to input your own api key

Related

Send data from Android to ESP32 with Bluetooth

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

My application crashes when asynctask process the code in android studio

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

Send and receive json obj in Android

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);

ad is not visible. not refreshing issue with admob in android fragments

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.

Editext inside ListItem not editable in android

I have made a ListView in that every ListItem is having EditText ,I want to edit them,But I am not able to edit them,Please help me for that,My code is as below,I have mentioned my java class(activity),Xml and raw file which will be binded to the ListView and adapter:
cart.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/hdr_cart"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/header_bg" />
<TextView
android:id="#+id/tv_title"
style="#style/font_med"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My cart"
android:textColor="#ff0000" />
<ImageView
android:id="#+id/iv_bak"
style="#style/iv_buyingrequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_back" />
</RelativeLayout>
<ListView
android:id="#+id/cart_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/tv_total"
android:layout_below="#+id/hdr_cart" />
<TextView
android:id="#+id/tv_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ll_botom"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:padding="5dp"
android:text="Total:"
android:textSize="20dp" />
<LinearLayout
android:id="#+id/ll_botom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
android:weightSum="2" >
<Button
android:id="#+id/tv_place_order"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/bg_blu_btn_selector"
android:gravity="center"
android:padding="8dp"
android:text="Place Order"
android:textColor="#ffffff"
android:textSize="16dp"
android:textStyle="bold" />
<Button
android:id="#+id/tv_home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/bg_blu_btn_selector"
android:gravity="center"
android:padding="8dp"
android:text="Continue Shopping"
android:textColor="#ffffff"
android:textSize="16dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
raw.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:padding="10dp" >
<ImageView
android:id="#+id/iv_product_img"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="left"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="product Name"
android:textColor="#545454"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Quantity:"
android:textColor="#000000"
android:textSize="12dp" />
<EditText
android:id="#+id/et_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_qty"
android:background="#drawable/blk_editext"
android:ems="4"
android:gravity="center_vertical"
android:text="200"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_label"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/et_qty"
android:text="Acre"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_wholesale_proce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Price:"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_wprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/et_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_wholesale_proce"
android:text="100"
android:textColor="#545454"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_retail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_wprice"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/iv_product_img"
android:text="Sub Total:"
android:textColor="#000000"
android:textSize="12dp" />
<TextView
android:id="#+id/tv_rprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_wprice"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/tv_retail"
android:text="100"
android:textColor="#545454"
android:textSize="12dp" />
<TextView
android:id="#+id/pro_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/min_qty"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/fob_price"
android:text=""
android:textColor="#cecece"
android:textSize="12dp" />
</RelativeLayout>
cartList.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
String total, pid;
TextView tv_total;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
tv_total = (TextView) findViewById(R.id.tv_total);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
System.out.println("::::::::::::Long click:::::::::::::::::");
pid = cartList.get(position).get(Const.TAG_PRODUCT_ID);
showCustomeAlert(CartListActivity.this, "Are You Sure want to delete?", "Yehki", "No", "Yes", position, pid);
return false;
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, CartPlaceOrderActivity.class);
startActivity(in);
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
StringBuilder b = new StringBuilder();
for (int i = 0; i > cartContent.getCount(); i++)
b.append(cartContent.getItem(i));
tv_total.setText("Total:" + total);
}
}
public void showCustomeAlert(final Context context, String message, String title, String leftButton, String rightButton, final int position, final String pid2) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup_alert_delete);
dialog.setCancelable(true);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView txt_message = (TextView) dialog.findViewById(R.id.txtMessage);
final Button btn_left = (Button) dialog.findViewById(R.id.btnLeft);
final Button btn_right = (Button) dialog.findViewById(R.id.btnRigth);
TextView txtTitle = (TextView) dialog.findViewById(R.id.txtTitle);
txtTitle.setText(title);
txt_message.setText(message);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
btn_left.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
btn_right.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String pid = cartList.get(position).get(Const.TAG_PRODUCT_ID);
cartList.clear();
new RemoveCart().execute(pid2);
cartContent.notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
/*
* Remove from cart List.........!!!
*/
private class RemoveCart extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_REMOVE_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_id=" + arg0[0];
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
total = jsonObj.getString(Const.TAG_TOTAL);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String subTotal = c.getString(Const.TAG_SUBTOTAL);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartProduct.put(Const.TAG_SUBTOTAL, subTotal);
cartProduct.put(Const.TAG_TOTAL, total);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
StringBuilder b = new StringBuilder();
for (int i = 0; i > cartContent.getCount(); i++)
b.append(cartContent.getItem(i));
tv_total.setText("Total:" + total);
}
}
}
cartAdapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.ui.WholesaleProductDetailActivity;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class CartAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> cartArray;
private Context mContext;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
String retailPrice;
String wholesalePrice;
String retailQty;
String wholesaleQty;
private ProgressDialog pDialog;
String status;
public CartAdapter(Context paramContext, ArrayList<HashMap<String, String>> cartList) {
this.mContext = paramContext;
this.cartArray = cartList;
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(paramContext));
options = new DisplayImageOptions.Builder().cacheOnDisc(true).showStubImage(R.drawable.logo).showImageOnFail(R.drawable.ic_launcher).build();
}
public int getCount() {
return this.cartArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_cart, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.pid = ((TextView) paramView.findViewById(R.id.pro_id));
localViewholder.proImg = ((ImageView) paramView.findViewById(R.id.iv_product_img));
localViewholder.proName = ((TextView) paramView.findViewById(R.id.product_label));
localViewholder.price = ((TextView) paramView.findViewById(R.id.tv_wprice));
localViewholder.qty = ((EditText) paramView.findViewById(R.id.et_qty));
localViewholder.subTotal = ((TextView) paramView.findViewById(R.id.tv_rprice));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println("::::::::::::::array indexes::::::::::::" + cartArray.get(paramInt));
retailQty = cartArray.get(paramInt).get(Const.TAG_MIN_ORDER_QTY_RETAIL);
retailPrice = cartArray.get(paramInt).get(Const.TAG_RETAIL_PRICE);
wholesaleQty = cartArray.get(paramInt).get(Const.TAG_MIN_ORDER_QTY_WHOLESALE);
wholesalePrice = cartArray.get(paramInt).get(Const.TAG_WHOLESALE_PRICE);
localViewholder.proName.setText(cartArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.pid.setText(cartArray.get(paramInt).get(Const.TAG_PRODUCT_ID));
localViewholder.pid.setVisibility(View.GONE);
localViewholder.qty.setText(cartArray.get(paramInt).get(Const.TAG_QUANTITY));
localViewholder.subTotal.setText(cartArray.get(paramInt).get(Const.TAG_SUBTOTAL));
/*
* for changing the price based on quantity....
*/
localViewholder.price.setText(cartArray.get(paramInt).get(Const.TAG_WHOLESALE_PRICE));
imageLoader.displayImage(cartArray.get(paramInt).get(Const.TAG_PRODUCT_IMG), localViewholder.proImg, options);
return paramView;
}
static class Viewholder {
ImageView proImg;
TextView proName;
TextView price;
TextView subTotal;
TextView pid;
EditText qty;
}
}
Use
myListView.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> listView, View view, int position, long id)
{
EditText yourEditText = (EditText) view.findViewById(R.id.youredittextid);
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
yourEditText.requestFocus();
}
});
The problem is that the selection of the row takes the focus but in order to edit the EditText you need focus on it

Categories