hi my app is ood but when i hav not internet and cant load data from my database
my app will be force close
my error is in emulatur
130 - AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
and
153- if(!result.equals("")){
in this java activity
HTML:
package com.smartapp.soton;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.widget.PullRefreshLayout;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;
import com.koushikdutta.async.http.socketio.ExceptionCallback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class Frag_Banners_All extends Fragment {
// Development by SmartMob (Manager : Mohammad Mokhles)
View v ;
Context context ;
GridView gridView ;
public List<HashMap<String , Object>> hash_all ;
String[] items ;
Ad ad ;
int preLast ;
int page = 0 ;
View row ;
ImageView row_list_img1 ;
TextView row_list_title , row_list_price , row_list_time ;
CardView row_list_card ;
PullRefreshLayout refresh ;
[user=3869344]@nullable[/user]
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, [user=3869344]@nullable[/user] ViewGroup container, [user=3869344]@nullable[/user] Bundle savedInstanceState) {
v = inflater.inflate(R.layout.frag_banners_all,container,false);
context = v.getContext();
hash_all = new ArrayList<>();
items = new String[hash_all.size()];
ad = new Ad();
gridView = (GridView)v.findViewById(R.id.grid_all);
gridView.setAdapter(ad);
gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
[user=439709]@override[/user]
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
[user=439709]@override[/user]
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(totalItemCount>=10){
final int lastItem = firstVisibleItem + visibleItemCount ;
if(lastItem == totalItemCount){
if(preLast != lastItem){
preLast = lastItem ;
page = page + 1 ;
try {
get_banners(page);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
});
page = 0 ;
preLast = 0 ;
CheckNet();
refresh = (PullRefreshLayout)v.findViewById(R.id.refresh);
refresh.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
[user=439709]@override[/user]
public void onRefresh() {
page = 0 ;
preLast = 0 ;
CheckNet();
}
});
return v;
}
private void get_banners(final int pages){
MainActivity.wait.show();
AsyncHttpPost post = new AsyncHttpPost(
"this is my linke i removed"
);
post.setTimeout(5000);
MultipartFormDataBody body = new MultipartFormDataBody();
body.addStringPart("City",MainActivity.sp.getString("City",null));
body.addStringPart("Cate","all");
body.addStringPart("Page", String.valueOf(pages));
post.setBody(body);
try{
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
[user=439709]@override[/user]
public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {
CheckNet();
if(e != null){
MainActivity.activity.runOnUiThread(new Runnable() {
[user=439709]@override[/user]
public void run() {
try{
refresh.setRefreshing(false);
}catch (Exception e){
e.printStackTrace();
}
MainActivity.wait.dismiss();
Toast.makeText(MainActivity.activity, "خطا در برقراری اتصال با سرور !", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
});
}
if(!result.equals("")){
MainActivity.activity.runOnUiThread(new Runnable() {
[user=439709]@override[/user]
public void run() {
MainActivity.wait.dismiss();
if(page==0){
hash_all.clear();
}
items.clone();
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0 ;i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
HashMap<String , Object> hash_add = new HashMap<String, Object>();
hash_add.put("ID",object.getString("ID"));
hash_add.put("Username",object.getString("Username"));
hash_add.put("Title",object.getString("Title"));
hash_add.put("Descript",object.getString("Descript"));
hash_add.put("Price",object.getString("Price"));
hash_add.put("Tell",object.getString("Tell"));
hash_add.put("Email",object.getString("Email"));
hash_add.put("City",object.getString("City"));
hash_add.put("Cate",object.getString("Cate"));
hash_add.put("Img1",object.getString("Img1"));
hash_add.put("Img2",object.getString("Img2"));
hash_add.put("Img3",object.getString("Img3"));
hash_add.put("Date",object.getString("Date"));
hash_all.add(hash_add);
items = new String[hash_all.size()];
}
ad.notifyDataSetChanged();
refresh.setRefreshing(false);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
public class Ad extends ArrayAdapter<String>{
private LayoutInflater inflater = null ;
public Ad(){
super(context,R.layout.row_list);
inflater = (LayoutInflater)MainActivity.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
[user=439709]@override[/user]
public int getCount() {
return items.length;
}
[user=923100]@Nonnu[/user]ll
[user=439709]@override[/user]
public View getView(int position, View convertView, ViewGroup parent) {
row = convertView ;
if(convertView == null){
row = inflater.inflate(R.layout.row_list,parent,false);
}
row_list_img1 = (ImageView)row.findViewById(R.id.row_list_img1);
row_list_title = (TextView) row.findViewById(R.id.row_list_title);
row_list_price = (TextView)row.findViewById(R.id.row_list_price);
row_list_time = (TextView)row.findViewById(R.id.row_list_time);
row_list_card = (CardView) row.findViewById(R.id.row_list_card);
final HashMap<String , Object> hash_get = (HashMap<String , Object>) hash_all.get(position);
row_list_title.setText(hash_get.get("Title").toString());
row_list_price.setText(hash_get.get("Price").toString()+" تومان");
if(Integer.parseInt(hash_get.get("Date").toString())<=59){
if(hash_get.get("Date").toString().equals("0") || hash_get.get("Date").toString().equals("1")){
row_list_time.setText("همین الان");
}else {
row_list_time.setText(hash_get.get("Date").toString()+" دقیقه پیش");
}
}else if(Integer.parseInt(hash_get.get("Date").toString())>=60 && Integer.parseInt(hash_get.get("Date").toString())<=1439){
int h = Integer.parseInt(hash_get.get("Date").toString())/60;
row_list_time.setText(h+" ساعت پیش");
}else if(Integer.parseInt(hash_get.get("Date").toString())>=1440 && Integer.parseInt(hash_get.get("Date").toString())<=43199){
int hh = Integer.parseInt(hash_get.get("Date").toString())/60/24;
row_list_time.setText(hh+" روز پیش");
}else if(Integer.parseInt(hash_get.get("Date").toString())>=43200 && Integer.parseInt(hash_get.get("Date").toString())<=518339){
int hhh = Integer.parseInt(hash_get.get("Date").toString())/60/24/30;
row_list_time.setText(hhh+" ماه پیش");
}else if(Integer.parseInt(hash_get.get("Date").toString())>=518340){
int hhhh = Integer.parseInt(hash_get.get("Date").toString())/60/24/30/12;
row_list_time.setText(hhhh+" سال پیش");
}
Picasso.with(MainActivity.activity)
.load(hash_get.get("Img1").toString())
.placeholder(R.mipmap.ic_launcher)
.into(row_list_img1);
row_list_card.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent(MainActivity.activity,Detail_Banners.class);
intent.putExtra("ID",hash_get.get("ID").toString());
intent.putExtra("Username",hash_get.get("Username").toString());
intent.putExtra("Title",hash_get.get("Title").toString());
intent.putExtra("Descript",hash_get.get("Descript").toString());
intent.putExtra("Price",hash_get.get("Price").toString());
intent.putExtra("Tell",hash_get.get("Tell").toString());
intent.putExtra("Email",hash_get.get("Email").toString());
intent.putExtra("City",hash_get.get("City").toString());
intent.putExtra("Cate",hash_get.get("Cate").toString());
intent.putExtra("Img1",hash_get.get("Img1").toString());
intent.putExtra("Img2",hash_get.get("Img2").toString());
intent.putExtra("Img3",hash_get.get("Img3").toString());
intent.putExtra("Date",hash_get.get("Date").toString());
startActivity(intent);
}
});
return row;
}
}
private void saeed(){
}
private void CheckNet(){
boolean connect = false ;
ConnectivityManager connectivityManager = (ConnectivityManager)MainActivity.activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
|| connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
connect = true ;
}else {
connect = false ;
}
if(connect==true){
try {
get_banners(page);
}catch (Exception e){
e.printStackTrace();
}
}else {
new MaterialDialog.Builder(MainActivity.activity)
.title("عدم اتصال به اینترنت")
.content("لطفا اتصال به اینترنت خود را بررسی کنید")
.positiveText("بررسی مجدد")
.negativeText("خروج")
.callback(new MaterialDialog.ButtonCallback() {
[user=439709]@override[/user]
public void onNegative(MaterialDialog dialog) {
super.onNegative(dialog);
MainActivity.activity.finish();
}
[user=439709]@override[/user]
public void onPositive(MaterialDialog dialog) {
super.onPositive(dialog);
CheckNet();
}
})
.show();
}
}
// Development by SmartMob (Manager : Mohammad Mokhles)
}
althing is ok but when i havent internet connection it will be force close
Related
I wrote a simple application to connect to a bluetooth mini keyboard but am having trouble with the BluetoothDevice.connect() call.
it gives discovery service failed. I have no problem using the bluetooth pairing and connect from the bluetooth settings menu. The same code works with a bluesnap serial to bluetooth device.
Am I missing something obvious?
I'm on galaxy tab froyo.
The code is:
Code:
package test.com;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
//import test.com.connect.ClientConnectThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class connect extends Activity {
static final int ALERT_DIALOG_ID = 1;
private BtReceiver btReceiver;
private BluetoothAdapter btAdapter;
private final Handler handler = new Handler();
private static final UUID SIMPLE_BT_APP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ClientConnectThread clientConnectThread;
private BluetoothDataCommThread bluetoothDataCommThread;
private BluetoothDevice remoteDevice;
private BluetoothSocket activeBluetoothSocket;
private final String deviceAddress="98:9A:10:12:03:6E";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btAdapter=BluetoothAdapter.getDefaultAdapter();
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "No Bluetooth Available",Toast.LENGTH_LONG ).show();
}else
{
if(!btAdapter.isEnabled())
{
Intent enableBtIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//REQUEST_ENABLE_BT is supposed to be 2 so
startActivityForResult(enableBtIntent, 2);
}
// we need a broadcast receiver now
btReceiver = new BtReceiver();
// register for state change broadcast events
IntentFilter stateChangedFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(btReceiver, stateChangedFilter);
// register for discovery events
IntentFilter actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(btReceiver, actionFoundFilter);
// check current state
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
}
}
public void findDevicesHandler(View view){
int currentState = btAdapter.getState();
if (currentState == BluetoothAdapter.STATE_ON) {
Toast.makeText(getApplicationContext(), "Finding devices",Toast.LENGTH_LONG ).show();
findDevices();
}
else
{
Toast.makeText(getApplicationContext(), "Adapter is off",Toast.LENGTH_LONG ).show();
}
}
protected void onActivityResult(int request,int result,Intent data)
{
if(result==RESULT_OK)
{
Toast.makeText(getApplicationContext(), "TURNING ON BLUETOOTH",Toast.LENGTH_LONG ).show();
}
}
public class BtReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
setStatus("Broadcast: Got ACTION_STATE_CHANGED");
int currentState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
if (currentState == BluetoothAdapter.STATE_ON) {
findDevices();
}
} else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
setStatus("Broadcast: Got ACTION_FOUND");
BluetoothDevice foundDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
setStatus("Device: " + foundDevice.getName() + "@" + foundDevice.getAddress());
remoteDevice=foundDevice;
if(remoteDevice.getAddress().equals(deviceAddress))
{
takeAction();
}
}
}
}
private void setStatus(String string){
Toast.makeText(getApplicationContext(), string,Toast.LENGTH_LONG ).show();
}
private void findDevices() {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevices) {
if (pairedDevice.getAddress().equals(deviceAddress)) {
setStatus("Found device: " + pairedDevice.getName() + "@" + deviceAddress);
remoteDevice = pairedDevice;
}
}
if (remoteDevice == null) {
setStatus("Starting discovery...");
if (btAdapter.startDiscovery()) {
setStatus("Discovery started...");
}
}
else
{
setStatus("Remote Device Address:"+remoteDevice.getAddress());
takeAction();
}
}
private void takeAction()
{
Toast.makeText(getApplicationContext(), "GETTING READY",Toast.LENGTH_LONG).show();
clientConnectThread = new ClientConnectThread(remoteDevice);
clientConnectThread.run();
}
@Override
protected void onDestroy() {
if (clientConnectThread != null) {
clientConnectThread.stopConnecting();
}
if (bluetoothDataCommThread != null) {
bluetoothDataCommThread.disconnect();
}
if (activeBluetoothSocket != null) {
try {
activeBluetoothSocket.close();
} catch (IOException e) {
//Log.e(DEBUG_TAG, "Failed to close socket", e);
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
btAdapter.cancelDiscovery();
this.unregisterReceiver(btReceiver);
super.onDestroy();
}
public void doStartDataCommThread() {
if (activeBluetoothSocket == null) {
setStatus("Can't start datacomm");
} else {
setStatus("Data comm thread starting");
bluetoothDataCommThread = new BluetoothDataCommThread(activeBluetoothSocket);
bluetoothDataCommThread.start();
}
}
private void setLastUsedRemoteBTDevice(String name) {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
Editor edit = prefs.edit();
edit.putString("LAST_REMOTE_DEVICE_ADDRESS", name);
edit.commit();
}
// client thread: used to make a synchronous connect call to a device
private class ClientConnectThread extends Thread {
private final BluetoothDevice remoteDevice;
private BluetoothSocket clientSocket;
public ClientConnectThread(BluetoothDevice remoteDevice) {
this.remoteDevice = remoteDevice;
clientSocket = null;
}
public void run() {
boolean success = false;
//success=true;
try {
btAdapter.cancelDiscovery();
//Method m = remoteDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createScoSocket",new Class[] { int.class});
//Method m = remoteDevice.getClass().getMethod("createInsecureRfcommSocket",new Class[] { int.class});
//clientSocket=(BluetoothSocket)m.invoke(remoteDevice,0);
clientSocket = remoteDevice.createRfcommSocketToServiceRecord(SIMPLE_BT_APP_UUID);
clientSocket.connect();
success = true;
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
try {
clientSocket.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(),"CLOSE:"+ e.toString(),Toast.LENGTH_LONG ).show();
}
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (NoSuchMethodException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} /*catch (IllegalAccessException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"CONNECT:"+ e.toString(),Toast.LENGTH_LONG ).show();
}*/
final String status;
if (success) {
status = "Connected to remote device";
activeBluetoothSocket = clientSocket;
// we don't need to keep listening
//serverListenThread.stopListening();
} else {
status = "Failed to connect to remote device";
activeBluetoothSocket = null;
}
handler.post(new Runnable() {
public void run() {
setStatus(status);
setLastUsedRemoteBTDevice(remoteDevice.getAddress());
doStartDataCommThread();
}
});
}
public void stopConnecting() {
try {
clientSocket.close();
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to stop connecting", e);
Toast.makeText(getApplicationContext(), "CLOSE2:"+e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
private class BluetoothDataCommThread extends Thread {
private final BluetoothSocket dataSocket;
private final InputStream inData;
public BluetoothDataCommThread(BluetoothSocket dataSocket) {
this.dataSocket = dataSocket;
InputStream inData = null;
try {
inData = dataSocket.getInputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
this.inData = inData;
}
public void run() {
byte[] readBuffer = new byte[64];
int readSize = 0;
try {
while (true) {
readSize=inData.read(readBuffer, 0, 24);
final String inStr = new String(readBuffer, 0, readSize);
handler.post(new Runnable() {
public void run() {
doHandleReceivedCommand(inStr);
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
public void disconnect() {
try {
dataSocket.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG ).show();
}
}
}
public void doHandleReceivedCommand(String rawCommand) {
String command = rawCommand.trim();
setStatus("Got: "+ command);
}
}
www.code.google.com
so it is right that not all bluetooth keyboard might work properly with any kind of android handheld....as yesterday i just read it in one of bluetooth keyboard
I'm trying to develop an app to scan for a BLE device. However, it only scans one time. I tried to use a while loop to loop it but it hangs there. The scanning part is at the proceed function:
Code:
package com.example.user.myfriend;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MainActivity extends ActionBarActivity {
BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello();
}
public void hello() {
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
proceed();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
proceed();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
int startByte = 2;
boolean patternFound = false;
while (startByte <= 5) {
if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && //Identifies an iBeacon
((int) scanRecord[startByte + 3] & 0xff) == 0x15) { //Identifies correct data length
patternFound = true;
break;
}
startByte++;
}
if (patternFound) {
//Convert to hex String
byte[] uuidBytes = new byte[16];
System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);
String hexString = bytesToHex(uuidBytes);
//Here is your UUID
String uuid = hexString.substring(0, 8) + "-" +
hexString.substring(8, 12) + "-" +
hexString.substring(12, 16) + "-" +
hexString.substring(16, 20) + "-" +
hexString.substring(20, 32);
//Here is your Major value
int major = (scanRecord[startByte + 20] & 0xff) * 0x100 + (scanRecord[startByte + 21] & 0xff);
//Here is your Minor value
int minor = (scanRecord[startByte + 22] & 0xff) * 0x100 + (scanRecord[startByte + 23] & 0xff);
if (major == 1) {
RelativeLayout hai = (RelativeLayout) findViewById(R.id.hai);
hai.setBackgroundColor(Color.YELLOW);
}
if (major == 2) {
RelativeLayout hai = (RelativeLayout) findViewById(R.id.hai);
hai.setBackgroundColor(Color.RED);
}
}
}
};
private static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public void proceed() {
boolean scanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
// @Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, 50000000);
}
Code:
Hi! I am currently doing on a project and I keep hitting the same error despite making changes. I have been hitting indexOutOfBound error and unable to delete my listView item because of that error. I am doing on Tab and Database. Can anyone help me with my error and problem? Thank you!!
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at itp231.dba.nyp.com.mabel_createchallenge.mabel_tabs.mabelUncompleted_Tab1$2.onClick(mabelUncompleted_Tab1.java:124)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here are by Java Codes
Code:
package itp231.dba.nyp.com.mabel_createchallenge;
import android.content.Context;
import android.database.Cursor;
import java.util.ArrayList;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_database.mabel_MyDBAdpater;
/*
* Created by Guest Account on 13/7/2016.
*/
public class mabel_creatingChallengeApp {
private static mabel_creatingChallengeApp ourInstance = new mabel_creatingChallengeApp();
public static mabel_creatingChallengeApp getInstance() {
return ourInstance;
}
public mabel_creatingChallengeApp() {
challengesCreatedAL = new ArrayList<mabel_challenges>();
}
//* for mabelUncompleted_tab1.java */
private ArrayList<mabel_challenges> challengesCreatedAL;
public ArrayList<mabel_challenges> getArray() {
return challengesCreatedAL;
} //getting the array from ArrayList<mabel_challenges>
public ArrayList<mabel_challenges> getChallengesCreatedAL() {
return challengesCreatedAL;
}
//add and delete entries in the database
//add to database
//context --> context of current state of the application/object
//call it to get information regarding another part of your program (activity and package/application)
public static long addToDatabase(mabel_challenges challenges, Context c) {
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
long rowIDofInsertEntry = db.insertEntry(challenges);
db.close();
return rowIDofInsertEntry;
}
public static boolean deleteFromDatabase(int rowID, Context c) {
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
boolean updateStatus = db.removeEntry(rowID);
db.close();
return updateStatus;
}
public static boolean updateDatabase(mabel_challenges cc, int rowID, Context c) {
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
boolean updateStatus = db.updateEntry(rowID, cc);
db.close();
return updateStatus;
}
//populate array --> retrieve the array
//get the context --> get the content from the page
//store all retrieve data from database
public void populateArrayFromDB(Context c) {
challengesCreatedAL.clear();
mabel_MyDBAdpater db = new mabel_MyDBAdpater(c);
db.open();
Cursor cur = db.retrieveAllEntriesCursor();
cur.moveToFirst();
while(cur.moveToNext()) {
int rowID = cur.getInt(mabel_MyDBAdpater.COLUMN_KEY_ID);
String nameOfChallenge = cur.getString(mabel_MyDBAdpater.COLUMN_NAME_ID);
String descOfChallenge = cur.getString(mabel_MyDBAdpater.COLUMN_DESC_ID);
String durationOfChallenge = cur.getString(mabel_MyDBAdpater.COLUMN_DURATION_ID);
mabel_challenges newChallenge = new mabel_challenges(rowID, nameOfChallenge, descOfChallenge, durationOfChallenge);
challengesCreatedAL.add(newChallenge);
}
db.close();
}
}
Code:
package itp231.dba.nyp.com.mabel_createchallenge.mabel_tabs;
/*
fragment is part of an activity
*/
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import itp231.dba.nyp.com.mabel_createchallenge.R;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_EditChallengeActivity;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_challengeDetailActivity;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_challenges;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_creatingChallengeApp;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_database.mabel_myChallengesListAdapter;
public class mabelUncompleted_Tab1 extends Fragment{
ListView listOfItemsLV;
ArrayList<mabel_challenges> challengesCreatedAL;
mabel_creatingChallengeApp cc;
public int selectedItem;
mabel_challenges c;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mabel_tab_1_uncompleted, container, false);
listOfItemsLV = (ListView) v.findViewById(R.id.challengesUncompletedLV);
registerForContextMenu(listOfItemsLV);
// addPage = (ImageButton) v.findViewById(R.id.addPage);
//calling out Instance Variable before the adapater
//to get challenges item on the list item
cc = mabel_creatingChallengeApp.getInstance();
//retrieve array from database
cc.populateArrayFromDB(getActivity().getApplicationContext()); //because is fragment so getActivity --> fragment is the contents in the tab -->getActivity will get the whole screen contents including contents in the tab
challengesCreatedAL = cc.getArray();
//Adapter for List View
mabel_myChallengesListAdapter challengesAdapter = new mabel_myChallengesListAdapter(getActivity(), challengesCreatedAL);
listOfItemsLV.setAdapter(challengesAdapter);
listOfItemsLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//getting the position of item in the array list
mabel_challenges c = challengesCreatedAL.get(i);
//intent for challenge detail
//mabel_challengeDetailActivity.class --> get to here
Intent viewDetailsIntent = new Intent(getActivity().getApplicationContext(), mabel_challengeDetailActivity.class);
//put extra --> Add extended data to the intent
viewDetailsIntent.putExtra(mabel_challenges.INTENT_NAME_CHALLENGENAME, c.getName());
viewDetailsIntent.putExtra(mabel_challenges.INTENT_NAME_DESCRIPTION, c.getDesc());
viewDetailsIntent.putExtra(mabel_challenges.INTENT_NAME_DURATION, c.getDuration());
viewDetailsIntent.putExtra("position", i);
startActivity(viewDetailsIntent);
}
});
return v;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Options");
menu.add(1,1,1, "Edit");
menu.add(1,2,2, "Delete");
}
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
selectedItem = menuInfo.position;
//mabel_challenges c = challengesCreatedAL.get(selectedItem);
switch(item.getItemId()) {
case 1:
//edit challenge
Intent editChallenge = new Intent (getActivity(), mabel_EditChallengeActivity.class);
editChallenge.putExtra(mabel_challenges.INTENT_NAME_ARRAY_ITEM, selectedItem);
startActivity(editChallenge);
break;
case 2:
//delete challenge
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
dialogBuilder.setMessage("Confirm delete ?");
dialogBuilder.setPositiveButton("Delete" ,new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mabel_myChallengesListAdapter challengeAdapter = new mabel_myChallengesListAdapter(getActivity().getApplicationContext(), challengesCreatedAL);
listOfItemsLV.setAdapter(challengeAdapter);
challengeAdapter.notifyDataSetChanged();
//prac 7b sales tracker -->delete the item
//selectedItem is the index of the array
mabel_creatingChallengeApp ca = mabel_creatingChallengeApp.getInstance();
int challengeId = ca.getArray().get(selectedItem).getId();
mabel_creatingChallengeApp.deleteFromDatabase(challengeId, getActivity().getApplicationContext());
ca.populateArrayFromDB(getActivity().getApplicationContext());
Toast.makeText(getActivity().getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
}
});
dialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// dialogBuilder.setCancelable(true);
Toast.makeText(getActivity().getApplicationContext(), "Cancelled!", Toast.LENGTH_LONG).show();
}
});
dialogBuilder.create();
dialogBuilder.show();
break;
}
return true;
}
@Override
public void onResume() {
super.onResume();
cc.populateArrayFromDB(getActivity().getApplicationContext());
}
}
Code:
package itp231.dba.nyp.com.mabel_createchallenge.mabel_database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_challenges;
import itp231.dba.nyp.com.mabel_createchallenge.mabel_creatingChallengeApp;
/**
* Created by Guest Account on 13/7/2016.
* for uncompleted Tab
*/
public class mabel_MyDBAdpater {
private static final String DATABASE_NAME = "Challenges.db"; //name of database
private static final String DATABASE_TABLE = "ChallengesDatabase"; //database table name
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase _db; //sqlite database handler
private final Context context; //current context
public static final String KEY_ID = "_id";
public static final int COLUMN_KEY_ID = 0;
public static final String ENTRY_CHALLENGE_NAME = "Name"; //name of column
public static final int COLUMN_NAME_ID = 1; //retrieval, position
public static final String ENTRY_CHALLENGE_DESC = "Description";
public static final int COLUMN_DESC_ID = 2;
public static final String ENTRY_CHALLENGE_DURATION = "Duration";
public static final int COLUMN_DURATION_ID = 3;
protected static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " " + "(" + KEY_ID + " integer primary key autoincrement, " +
ENTRY_CHALLENGE_NAME + " Text, " + ENTRY_CHALLENGE_DESC + " Text, " + ENTRY_CHALLENGE_DURATION + " Text);";
//making debugging easier
//a fix pid for Eclipse debugger
//open and close method
private String mabel_MyDBAdapter_LOG_CAT = "MY_LOG";
private MyDBOpenHelper dbHelper;
public mabel_MyDBAdpater(Context _context)
{
this.context = _context;
dbHelper = new MyDBOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION); //help to create object
}
public void close()
{
_db.close();
Log.w(mabel_MyDBAdapter_LOG_CAT, "DB closed");
}
public void open() throws SQLiteException
{
try
{
_db = dbHelper.getWritableDatabase();
Log.w(mabel_MyDBAdapter_LOG_CAT, "DB opened as writable database");
}
catch(SQLiteException e)
{
_db = dbHelper.getReadableDatabase();
Log.w(mabel_MyDBAdapter_LOG_CAT, "DB opened as readable database");
}
}
public long insertEntry(mabel_challenges cc)
{
// Create a new record
ContentValues newEntryValues = new ContentValues();
// Assign values for each row
newEntryValues.put(ENTRY_CHALLENGE_NAME, cc.getName());
newEntryValues.put(ENTRY_CHALLENGE_DESC, cc.getDesc());
newEntryValues.put(ENTRY_CHALLENGE_DURATION, cc.getDuration());
// Insert the row
Log.w(mabel_MyDBAdapter_LOG_CAT, "Inserted EntryName = " + cc.getName()
+ " EntryDesc = " + cc.getDesc() + " EntryDuration = " + cc.getDuration() + " into table " + DATABASE_TABLE);
return _db.insert(DATABASE_TABLE, null, newEntryValues);
}
//removing data
public boolean removeEntry(long _rowIndex)
{
if (_db.delete(DATABASE_TABLE, KEY_ID + " = " + _rowIndex, null) <= 0)
{
Log.w(mabel_MyDBAdapter_LOG_CAT, "Removing entry where id = "
+ _rowIndex + " Failed");
return false;
}
Log.w(mabel_MyDBAdapter_LOG_CAT, "Removing entry where id = "
+ _rowIndex + " Success");
return true;
}
//update method
public boolean updateEntry(long rowIndex, mabel_challenges cc) {
ContentValues updateValues = new ContentValues();
mabel_creatingChallengeApp ca = mabel_creatingChallengeApp.getInstance();
updateValues.put(ENTRY_CHALLENGE_NAME, cc.getName());
updateValues.put(ENTRY_CHALLENGE_DESC, cc.getDesc());
updateValues.put(ENTRY_CHALLENGE_DURATION, cc.getDuration());
String where = KEY_ID + "=" + rowIndex; //selected id for updating data
Log.w(mabel_MyDBAdapter_LOG_CAT, "Updated Challenge Name = " + cc.getName() + "Update Challenge Description = " + cc.getDesc() + "Update Duration = " + cc.getDuration() + " into table " +DATABASE_TABLE);
if (_db.update(DATABASE_TABLE, updateValues, where, null) <= 0) {
return true; //return success
}
return false; //newer update anything
}
//retrieve method
public Cursor retrieveAllEntriesCursor()
{
Cursor c = null;
try
{
c = _db.query(DATABASE_TABLE, new String[] {KEY_ID,ENTRY_CHALLENGE_NAME, ENTRY_CHALLENGE_DESC, ENTRY_CHALLENGE_DURATION}, null, null, null, null, null);
}
catch(SQLiteException e)
{
Log.w(mabel_MyDBAdapter_LOG_CAT, "Retrieve fail!");
}
return c;
}
public class MyDBOpenHelper extends SQLiteOpenHelper
{
public MyDBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override //compulsory method
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
Log.w(mabel_MyDBAdapter_LOG_CAT, "Helper : DB " + DATABASE_TABLE + " Created!!");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
} // End of myDBOpenHelper
}
Can help me to see what's wrong? Thank you !!!!
I can't read the all code, it's too long, but ai think that you want to access for example array [5], but array length is smaller.
Trimis de pe al meu Sony Z2 D6503
mabelll said:
Hi! I am currently doing on a project and I keep hitting the same error despite making changes. I have been hitting indexOutOfBound error and unable to delete my listView item because of that error. I am doing on Tab and Database. Can anyone help me with my error and problem? Thank you!!
Click to expand...
Click to collapse
Uncompleted_Tab1 onClick(mabelUncompleted _Tab1.java:124)
cannot see the line number. check line 124 for yourself.
How to add image and text to both parentgroup and childgroup of expandablelistview dynamically from database.T his code uses expendable listview. I want to display image and text to parentgroup and childgroup of expendablelistview dynamically from database. i am a newbie in android development so please some one help me out.
This is my code:
public class CustomListAdapter15 extends BaseExpandableListAdapter {
List<HashMap<String, Object>> models, models2;
Context context;
LayoutInflater inflater;
ViewHolder viewHolder;
View view1;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
public CustomListAdapter15(Context context, List<HashMap<String, Object>> models2, List<HashMap<String, Object>> models) {
this.context = context;
this.models2 = models2; //parentItems
this.models = models; //childtems
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt = null;
public ImageView likem = null, createButton;
//RelativeLayout rel, rel2;
LinearLayout rel;
private Button btnSend;
}
public void clear() {
if (models != null)
models.clear();
}
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
@override
public Object getChild(int groupPosition, int childPosition) {
//return null;
//return models.get((HashMap<String, Object>)models2.get(groupPosition)).get(childPosition);
return models.get(groupPosition).get(childPosition);
}
@override
public long getChildId(int groupPosition, int childPosition) {
//return 0;
return childPosition;
}
@override
public int getChildrenCount(int groupPosition) {
return ((HashMap<String, Object>) models.get(groupPosition)).size();
//return models.size();
}
@override
public Object getGroup(int groupPosition) {
//return null;
return models2.get(groupPosition);
}
@override
public int getGroupCount() {
return models2.size();
}
@override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
@override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
@override
public long getGroupId(int groupPosition) {
//return 0;
return groupPosition;
}
@override
public boolean hasStableIds() {
return true;
}
@override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
public HashMap<String, Object> getItem1(int position2) {
return models2.get(position2);
}
/ @override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}*/
@override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.chat_right, null);
/*if(session_ph.equals((sphon)))
{
view = inflater.inflate(R.layout.chat_right, parent, false);
}
else if(!session_ph.equals((sphon)))
{
view = inflater.inflate(R.layout.chat_left, parent, false);
}*/
//view.setBackgroundColor(color_arr[pos]);
viewHolder = new ViewHolder();
/* viewHolder.gppho=(TextView)view.findViewById(R.id.gphn);
viewHolder.gadminph=(TextView)view.findViewById(R.id.gadphn);
viewHolder.rel = (LinearLayout)view.findViewById(R.id.comrel);*/
gppho = (TextView) view.findViewById(R.id.gphn);
gadminph = (TextView) view.findViewById(R.id.gadphn);
viewHolder.rel = (LinearLayout) view.findViewById(R.id.comrel);
// rel1 = (LinearLayout)view.findViewById(R.id.comrel);
/* HashMap<String, Object> item = models.get(position);
gppho.setText((CharSequence) item.get("SPHON"));
gadminph.setText((CharSequence) item.get("GAPHON"));
String gadm_ph=gadminph.getText().toString();
String sendersphon=gppho.getText().toString();
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) rel1.getLayoutParams();
if(gadm_ph.equals((sendersphon)))
{
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
rel1.setLayoutParams(layoutParams);
rel1.setBackground(getResources().getDrawable(R.drawable.bubble2_out));
//v1iew = inflater.inflate(R.layout.chat_right, parent, false);
}
else if(!gadm_ph.equals((sendersphon)))
{
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT,RelativeLayout.TRUE);
rel1.setLayoutParams(layoutParams);
rel1.setBackground(getResources().getDrawable(R.drawable.bubble1_in));
//view = inflater.inflate(R.layout.chat_left, parent, false);
}*/
viewHolder.rel.setOnLongClickListener(new View.OnLongClickListener() {
@override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
int position = (Integer) v.getTag();
HashMap<String, Object> item = models2.get(position);
gppho.setText((CharSequence) item.get("SPHON"));
gadminph.setText((CharSequence) item.get("GAPHON"));
String gadm_ph1 = gadminph.getText().toString();
String sendersphon1 = gppho.getText().toString();
gpida.setText((CharSequence) item.get("GID"));
pacmos = gpida.getText().toString();
Toast.makeText(Group_create_view_adm.this, gadm_ph1, Toast.LENGTH_SHORT).show();
Toast.makeText(Group_create_view_adm.this, sendersphon1, Toast.LENGTH_SHORT).show();
// removeItemFromList();
return true;
}
});
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.rel.setTag(childPosition);
final HashMap<String, Object> item = getItem(childPosition);
/* name.setText(((String)item.get(R.id.name)));
*
*/
gpida = (TextView) view.findViewById(R.id.gid);
gpnam = (TextView) view.findViewById(R.id.gnam);
gadminph = (TextView) view.findViewById(R.id.gadphn);
gpema = (TextView) view.findViewById(R.id.gema);
gppho = (TextView) view.findViewById(R.id.gphn);
namesa = (TextView) view.findViewById(R.id.senname);
msgsa = (TextView) view.findViewById(R.id.txt_msg);
tims = (TextView) view.findViewById(R.id.sentime);
imga = (ImageView) view.findViewById(R.id.gperimg);
gpida.setText((CharSequence) item.get("GID"));
gpnam.setText((CharSequence) item.get("GNAME"));
gadminph.setText((CharSequence) item.get("GAPHON"));
gpema.setText((CharSequence) item.get("SEMAIL"));
gppho.setText((CharSequence) item.get("SPHON"));
namesa.setText((CharSequence) item.get("SNAME"));
msgsa.setText((CharSequence) item.get("SCOMM"));
tims.setText((CharSequence) item.get("STIM"));
Picasso.with(context)
//.load("PIC")
.load((String) item.get("GPRIMG"))
// .centerCrop()
// .fit()
.into(imga);
rel1 = (LinearLayout) view.findViewById(R.id.comrel);
gadm_ph = gadminph.getText().toString();
sendersphon = gppho.getText().toString();
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (session_ph.equals((sendersphon))) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
rel1.setLayoutParams(layoutParams);
//rel1.setGravity(Gravity.RIGHT);
rel1.setBackground(getResources().getDrawable(R.drawable.bubble2_out));
//v1iew = inflater.inflate(R.layout.chat_right, parent, false);
} else if (!session_ph.equals((sendersphon))) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
rel1.setLayoutParams(layoutParams);
// rel1.setGravity(Gravity.LEFT);
rel1.setBackground(getResources().getDrawable(R.drawable.bubble1_in));
//view = inflater.inflate(R.layout.chat_left, parent, false);
}
if(childPosition == getChildrenCount(groupPosition)-1)
{
view = inflater.inflate(R.layout.chat_left,null);
viewHolder.btnSend =(Button)view.findViewById(R.id.btn_chat_send);
editText = (EditText)view.findViewById(R.id.msg_type);
//TextView txtFooter = (TextView)view.findViewById(R.id.txtFooter);
//txtFooter.setText(currentParent.textToFooter);
}
viewHolder.btnSend.setOnClickListener(new View.OnClickListener(){
@override
public void onClick(View v) {
int position = (Integer) v.getTag();
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(Group_create_view_adm.this, "Please input some text...", Toast.LENGTH_LONG).show();
} else {
HashMap<String, Object> item = models.get(position);
pho.setText((CharSequence) item.get("PHON"));
pacm11=pho.getText().toString();
msg=editText.getText().toString();
new LoadAllProducts95().execute();
}
}
});
return view;
}
@override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
view1 = convertView;
if(view1==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view1 = inflater.inflate(R.layout.groupss_view_row, null);
//view.setBackgroundColor(color_arr[pos]);
viewHolder = new ViewHolder();
viewHolder.createButton = (ImageView)view1.findViewById(R.id.pic123df);
viewHolder.createButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int position = (Integer) v.getTag();
HashMap<String, Object> item = models.get(position);
pho.setText((CharSequence) item.get("PHON"));
pacm=pho.getText().toString();
Intent intent = new Intent(context, Friendsprofile2.class);
intent.putExtra("TITLE", pacm);
//Intent putExtra = intent.putExtra("title", item.get(pac));
//intent.putExtra("image", item.getImage());
//Start details activity
context.startActivity(intent);
}
});
view1.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) view1.getTag();
}
viewHolder.createButton.setTag(groupPosition);
// viewHolder.rel.setTag(position);
//viewHolder.rel2.setTag(position);
final HashMap<String, Object> item = getItem1(groupPosition);
/* name.setText(((String)item.get(R.id.name)));
*
*/
// like = (ImageView) view.findViewById(R.id.like);
//sharingButton = (ImageButton) view.findViewById(R.id.share);
//text =(TextView)view.findViewById(R.id.text123);
name=(TextView)view1.findViewById(R.id.name);
idam=(TextView)view1.findViewById(R.id.id);
pho=(TextView)view1.findViewById(R.id.phon);
pic =(ImageView)view1.findViewById(R.id.pic123df);
bio=(TextView)view1.findViewById(R.id.bio);
//gtot=(TextView)view.findViewById(R.id.gptat);
name.setText((CharSequence) item.get("NAME"));
idam.setText((CharSequence) item.get("IDAC"));
pho.setText((CharSequence) item.get("PHON"));
bio.setText((CharSequence) item.get("BIOK"));
//gtot.setText((CharSequence) item.get("GPTAT"));
// text.setText((CharSequence) item.get("TEXT"));
//rel=(RelativeLayout)view.findViewById(R.id.frpos);
sapar=(TextView)view1.findViewById(R.id.sap);
gree = (ImageView)view1.findViewById(R.id.green);
sapar.setText((CharSequence) item.get("STAT"));
stato=sapar.getText().toString();
phoneno=pho.getText().toString();
//abc=Integer.parseInt(stato);
if((stato.equals(1)))
{
// Toast.makeText(context, "abc", Toast.LENGTH_LONG).show();
Picasso.with(context)
//.load("PIC")
.load(R.mipmap.green)
.resize(30, 30)
// .centerCrop()
// .fit()
.into(gree);
// Toast.makeText(context, phoneno, Toast.LENGTH_LONG).show();
}
else if(!stato.equals(1))
{
// Toast.makeText(context, "koll", Toast.LENGTH_LONG).show();
Picasso.with(context)
//.load("PIC")
.load(R.mipmap.gray)
.resize(30, 30)
// .centerCrop()
// .fit()
.into(gree);
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.resize(150, 150)
// .centerCrop()
// .fit()
.into(pic);
return view1;
}
}
Hey guys, I am having problem with deleting the childview from my expandablelistview. It deletes (I think), however, when I add a new childview, it is the exact same as the one I just deleted.
youtu.be/eJjR9FEpaaY
codes below
My activity
Code:
public class PlanSetterAct extends AppCompatActivity {
private Button nextBtn;
private EditText planName, weekNum;
private ExpandableListView weekdayList;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private PlanSetterListAdapter adapter;
private int childCount = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.plan_setter);
weekdayList = (ExpandableListView) findViewById(R.id.plan_setter_exercise_list);
nextBtn = (Button) findViewById(R.id.plan_next_btn);
planName = (EditText) findViewById(R.id.plan_name_edit);
weekNum = (EditText) findViewById(R.id.plan_num_edit);
prepareNextButton();
prepareExerciseList();
adapter = new PlanSetterListAdapter(this.getApplicationContext(),listDataHeader,listDataChild);
weekdayList.setAdapter(adapter);
exerciseListChildListener();
}
private void prepareNextButton(){
nextBtn.animate().setDuration(1000);
nextBtn.animate().translationXBy(-500);
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(Checker.hasText(planName) && Checker.isNum(weekNum)){
Utilities.setButtonClickColor(nextBtn, Color.GREEN);
startActivity(new Intent(PlanSetterAct.this, UserMainAct.class));
finish();
Utilities.debugLog("Moving to UserMainAct");
}else{
Utilities.setButtonClickColor(nextBtn, Color.RED);
}
}
});
}
private void prepareExerciseList() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Monday");
listDataHeader.add("Tuesday");
listDataHeader.add("Wednesday");
listDataHeader.add("Thursday");
listDataHeader.add("Friday");
listDataHeader.add("Saturday");
listDataHeader.add("Sunday");
for(int i = 0; i < listDataHeader.size(); i++) {
listDataChild.put(listDataHeader.get(i), new ArrayList<String>());
}
}
private void exerciseListChildListener(){
weekdayList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
ExpandableListView expandableListView = (ExpandableListView) parent;
long pos = expandableListView.getExpandableListPosition(position);
int itemType = ExpandableListView.getPackedPositionType(pos);
int groupPosition = ExpandableListView.getPackedPositionGroup(pos);
int childPosition = ExpandableListView.getPackedPositionChild(pos);
List<String> parentGroup = listDataChild.get(listDataHeader.get(groupPosition));
if(itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP){
parentGroup.add(childPosition+"");
adapter.notifyDataSetChanged();
return true;
}else if(itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD){
debugLog("Parent position: " + groupPosition +" | child position: " + childPosition);
parentGroup.remove(childPosition);
adapter.notifyDataSetChanged();
return true;
}
return false;
}
});
}
}
My Adapter
Code:
public class PlanSetterListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader;
private HashMap<String, List<String>> listDataChild;
public PlanSetterListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listDataChild = listChildData;
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition))
.get(childPosititon);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final LayoutInflater inflater;
if (convertView == null) {
inflater= (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.add_exercise_layout, null);
}
final LinearLayout txtListChild = (LinearLayout) convertView.findViewById(R.id.plan_setter_add_exercise);
final LinearLayout addExerciseLayout = (LinearLayout) txtListChild.getChildAt(0);
Button okBtn = (Button) addExerciseLayout.getChildAt(1);
//init and gone from xml
okBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView errorView = (TextView) txtListChild.getChildAt(1);
TextView finalView = (TextView) txtListChild.getChildAt(2);
LinearLayout exerciseAddLayout = (LinearLayout) addExerciseLayout.getChildAt(0);
EditText exerciseNameEdit = ((EditText)exerciseAddLayout.getChildAt(0));
EditText exerciseLbsEdit = (EditText)exerciseAddLayout.getChildAt(2);
EditText exerciseRepsEdit = (EditText) exerciseAddLayout.getChildAt(4);
if(hasText(exerciseNameEdit) && isNum(exerciseLbsEdit) && isNum(exerciseRepsEdit)){
String exerciseNameStr = exerciseNameEdit.getText().toString();
String exerciseWeightStr = exerciseLbsEdit.getText().toString()+"lbs";
String exerciseRepsStr = exerciseLbsEdit.getText().toString()+"x";
finalView.setText(exerciseNameStr + " at " + exerciseWeightStr + " for " +exerciseRepsStr);
finalView.setTextSize(20);
//display
setVisibleAndAnimate(context,finalView);
addExerciseLayout.setVisibility(View.GONE);
errorView.setVisibility(View.GONE);
}else{
setVisibleAndAnimate(context,errorView);
}
}
});
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this.listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this.listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.expandable_list_parent, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}