I am using a ListView with CursorAdapter to display some information. Depending on the information type the row is different but in reality some items are right and some left.
Here is my Activity
package ;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.QuickContactBadge;
public class ConversationActivity extends BaseActivity implements
OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = ConversationActivity.class
.getSimpleName();
Cursor cursor; // 1
ListView conversationList; // 2
Button sendButton;
EditText newMessageText;
QuickContactBadge badge;
static String ID;
ConversationReceiver conversationReceiver = new ConversationReceiver();
private static final int LOADER_ID = 0x02;
private ConversationAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onStart() {
super.onStart();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conversation);
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
// Die Views suchen
conversationList = (ListView) findViewById(R.id.ConversationList);
sendButton = (Button) findViewById(R.id.Conv_buttonSendMessage);
newMessageText = (EditText) findViewById(R.id.Conv_newMessageText);
Intent intent = getIntent();
ID = intent.getStringExtra("ID");
sendButton.setOnClickListener(this);
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
Log.d(TAG, "Erstelle ActionBar fuer ID: " + ID);
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI };
ContentResolver resolver = getContentResolver();
String[] br_projection = new String[] { BaseColumns._ID,
"conv_type", "address", "Profile_ID" };
Cursor ConvCursor = resolver
.query(Uri
.parse("content://.../conversations"),
br_projection, BaseColumns._ID + " = ?",
new String[] { ID }, null);
ActionBar actionBar = getActionBar();
if (ConvCursor.moveToFirst()) {
String number = "";
number = ConvCursor.getString(ConvCursor
.getColumnIndexOrThrow("address"));
Log.v(TAG, "Nummer: " + number);
Uri contactUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor contactCursor = getContentResolver().query(
contactUri, projection, null, null, null);
Log.v(TAG, "contactCursor.moveToFirst");
if (contactCursor.moveToFirst()) {
// Get values from contacts database:
String ContactName = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
String ContactThumbnailString = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI));
ImageView logo = (ImageView) findViewById(android.R.id.home);
if (ContactThumbnailString != null) {
Uri ContactThumbnailURI = Uri
.parse(ContactThumbnailString);
logo.setImageURI(ContactThumbnailURI);
}
actionBar.setTitle(ContactName);
} else {
actionBar.setTitle(R.string.ContactNoName);
}
actionBar
.setSubtitle(PhoneNumberUtils.formatNumber(number));
}
}
} catch (Exception e) {
Log.e(TAG, "ConvAct Header Info ", e);
}
adapter = new ConversationAdapter(this, cursor);
conversationList.setAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(conversationReceiver);
}
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = new String[] { BaseColumns._ID, "item_type",
"send", "serverid", "direction", "date", "content", "sender",
"Conv_ID" };
Intent intent = getIntent();
return new CursorLoader(
this,
Uri.parse("content://.../items"),
projection, "Conv_ID = ?", new String[] { intent
.getStringExtra("ID") }, "date ASC");
}
#SuppressLint("NewApi")
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#SuppressLint("NewApi")
public void onLoaderReset(Loader<Cursor> cursorLoader) {
adapter.swapCursor(null);
}
// Wird bei Klicks auf den Button aufgerufen //
public void onClick(View v) {
Log.d(TAG, "Neues Item fuer ID: "+ID);
ContentResolver resolver = getContentResolver();
Cursor convCursor = resolver
.query(Uri
.parse("content://.../conversations/"
+ ID), new String[] { "address" }, null, null,
null);
convCursor.moveToFirst();
ContentValues values = new ContentValues();
values.clear();
values.put("item_type", "tm");
values.put("direction", "out");
values.put("send", "0");
values.put("date", String.valueOf(System.currentTimeMillis()));
values.put("content", newMessageText.getText().toString());
values.put("sender",
convCursor.getString(convCursor.getColumnIndex("address")));
values.put("Conv_ID", ID);
resolver.insert(Uri
.parse("content://.../items"),
values);
newMessageText.setText("");
}
}
Here is a part of my CursorAdapter
package ;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.QuickContactBadge;
import android.widget.TextView;
public class ConversationAdapter extends CursorAdapter {
private static final String TAG = ConversationAdapter.class.getSimpleName();
#SuppressWarnings("deprecation")
public ConversationAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
String item_direction = cursor.getString(cursor
.getColumnIndexOrThrow("direction"));
View v = null;
if (item_direction.equals("out")) {
v = inflater.inflate(R.layout.conversationrow_out, parent, false);
} else if (item_direction.equals("in")) {
v = inflater.inflate(R.layout.conversationrow_in, parent, false);
}
bindView(v, context, cursor);
return v;
}
#SuppressLint({ "InlinedApi", "NewApi" })
#Override
public void bindView(View row, Context context, Cursor cursor) {
String item_type = cursor.getString(cursor
.getColumnIndexOrThrow("item_type"));
Log.v(TAG, item_type);
Cursor contactCursor = null;
try {
TextView ConversationText = (TextView) row
.findViewById(R.id.ConversationText);
Log.v(TAG, "message selected");
// Definition
String[] projection;
String number, textContent = "";
Uri ThumbnailURI = null;
String ThumbnailString;
QuickContactBadge ConversationBadge = null;
Log.d(TAG,
"Nachricht mit Inhalt: "
+ cursor.getString(cursor
.getColumnIndexOrThrow("content"))
+ " in Richtung: "
+ cursor.getString(cursor
.getColumnIndexOrThrow("direction")));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI };
ConversationBadge = (QuickContactBadge) row
.findViewById(R.id.ConversationBadge);
} else {
projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };
}
Log.v(TAG, "Lese nun Nutzerdaten");
number = cursor.getString(cursor.getColumnIndexOrThrow("sender"));
Uri contactUri = Uri.withAppendedPath(
PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Log.v(TAG, "Nutzerdaten-Query");
contactCursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (contactCursor.moveToFirst()) {
String name = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
ConversationBadge.assignContactFromPhone(number, true);
ThumbnailString = contactCursor
.getString(contactCursor
.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI));
if (cursor.getString(
cursor.getColumnIndexOrThrow("direction")).equals(
"in")
&& ThumbnailString != null) {
ThumbnailURI = Uri.parse(ThumbnailString);
ConversationBadge.setImageURI(ThumbnailURI);
} else {
ConversationBadge.setImageToDefault();
}
}
// textContent = name+": ";
} else {
// textContent = number+": ";
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
ConversationBadge.setImageToDefault();
}
}
if (item_type.equals("tm")) {
textContent += (cursor.getString(cursor
.getColumnIndexOrThrow("content")));
}
ConversationText.setText(textContent);
TextView ConversationTime = (TextView) row
.findViewById(R.id.ConversationTime);
long timestamp = cursor.getLong(cursor.getColumnIndex("date"));
ConversationTime.setText(DateUtils
.getRelativeTimeSpanString(timestamp));
} catch (Exception e) {
Log.e(TAG, "bindView ", e);
} finally {
contactCursor.close();
}
}
}
When I open the Activity everything looks fine. Incomming messages appear left-adjusted and outgoing ones are right-adjusted (basicly). When I have a new message i call the above code to requery and update the list. The Content of the new item now appears on the bvottom as I like it but the layout of this last item seems to be the one of the intitial last. The layout for this new item appears on the top.
I would like to post images but I don't have enought reputation points. :(
Thanks
Related
I am a newbie to Android programming.I want to use data inputted into an SQLite database to populate an Android Listview. However, Android keeps highlighting the SimpleCursorAdapter below as error. Can anyone help?
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
Below is the full code:
package com.allmycode.databaseinsertwithlistview;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText GetName,GetPhoneNumber,GetSubject ;
Button Submit ;
String Name, PhoneNumber, Subject ;
Boolean CheckEditTextEmpty ;
String SQLiteQuery;
SQLiteDatabase SQLITEDATABASE;
TextView display;
Cursor cursor;
ListView listView;
//Make these declarations to enable the fetchallitems() method work
public static final String name = "name";
public static final String phone_number = "Phone_number";
public static final String subject = "subject";
private SimpleCursorAdapter dataAdapter;
private static final String demoTable = "demoTable";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);GetName = (EditText)findViewById(R.id.editText1);
GetPhoneNumber = (EditText)findViewById(R.id.editText2);
GetSubject = (EditText)findViewById(R.id.editText3);
listView = (ListView) findViewById(R.id.ListVw);
//display= (TextView) findViewById(R.id.textView) ;
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
DBCreate();
SubmitData2SQLiteDB();
displayListView();
}
});
}
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("DemoDataBase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS demoTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name String, phone_number String, subject String);");
}
public void SubmitData2SQLiteDB(){
Name = GetName.getText().toString();
PhoneNumber = GetPhoneNumber.getText().toString();
Subject = GetSubject.getText().toString();
CheckEditTextIsEmptyOrNot( Name,PhoneNumber, Subject);
if(CheckEditTextEmpty == true)
{
SQLiteQuery = "INSERT INTO demoTable (name,phone_number,subject) VALUES('"+Name+"', '"+PhoneNumber+"', '"+Subject+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(MainActivity.this,"Data Submit Successfully", Toast.LENGTH_LONG).show();
ClearEditTextAfterDoneTask();
// addtoTextView();
}
else {
Toast.makeText(MainActivity.this,"Please Fill All the Fields", Toast.LENGTH_LONG).show();
}
}
public void CheckEditTextIsEmptyOrNot(String Name,String PhoneNumber, String subject ){
if(TextUtils.isEmpty(Name) || TextUtils.isEmpty(PhoneNumber) || TextUtils.isEmpty(Subject)){
CheckEditTextEmpty = false ;
}
else {
CheckEditTextEmpty = true ;
}
}
public void ClearEditTextAfterDoneTask(){
GetName.getText().clear();
GetPhoneNumber.getText().clear();
GetSubject.getText().clear();
}
/* void addtoTextView(){
cursor= SQLITEDATABASE.rawQuery("SELECT * FROM demoTable;",null);
if (cursor !=null && cursor.moveToFirst()){
String name;
do{
name = cursor.getString(0);
String pnone_number=cursor.getString(1);
String test2=cursor.getString(2);
String test3 = cursor.getString(3);
display.append(name + " " + pnone_number +" "+test2 +" "+ test3 +"\n");
} while (cursor.moveToNext());
}
display.append("-------------\n");
} */
public Cursor fetchAllItems() {
Cursor mCursor = SQLITEDATABASE.query(this.demoTable, new String[] {this.name,
this.phone_number, this.subject},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
private void displayListView()
{
Cursor cursor= fetchAllItems();
//The desired columns to be bound
String[] columns=new String[]{
this.name,
this.phone_number,
this.subject
};
//The XML defined views which the data will be bound to
int[] to = new int[] {
R.id.name,
R.id.phone_number,
R.id.subject,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.secondview,
cursor,
columns,
to,
0);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
}
What i am trying to do is getting images from gallery and camera and placing it in an recyclerview.
Now main parts comes after image is now placedd in the recyclerview ,
but can anyone just tell me how can i get back these images shown in the recyclerview back to the mainActivity only when i click my upload button.
Thank you in advance.
My Main Activity.
package www.welkinfort.com.pphc;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import butterknife.ButterKnife;
public class XenImageUploading extends AppCompatActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {
ArrayAdapter<String> des_dataAdapter;
ArrayList<String> discription_list = new ArrayList<>();
//#BindView(R.id.selct_prject_spinner)
Spinner select_pro_spn;
TextView datetextTextView;
Calendar myCalendar;
static Bitmap rotatedBitmap;
static Bitmap finalrotatedBitmap;
DatePickerDialog.OnDateSetListener date;
static final int REQUEST_TAKE_PHOTO = 1;
private int SELECT_FILE = 2;
private static String bitmap_overdraw_str;
private static ImageButton cameraclick;
private static ImageButton galleryclick;
private static ImageButton videoclick;
private static String mCurrentPhotoPath;
private static RecyclerView recyclerView;
ArrayList<Data_Model> arrayList;
ImageView image_view;
MyAdapter m;
Bitmap finalbitmap;
static String clickpath;
int i = 0;
String path ;
private static final String TAG = "XenImageUploading";
static File photoFile_1 = null;
private String userChoosenTask;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xen_image_upload);
ButterKnife.bind(this);
setTitle("XEN IMAGE UPLOAD");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
cameraclick = (ImageButton) findViewById(R.id.camera_btn);
galleryclick = (ImageButton) findViewById(R.id.gallery_btn);
image_view = (ImageView) findViewById(R.id.image_view);
arrayList = new ArrayList<>();
Log.d("oncreate", "set adapter");
bitmap_overdraw_str = "Lat:" + "aaaaaaaa" + "\nLong:" + "aaaaaaaa" + "\nDate:" + "aaaaaaaa";
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
///////////////////////////////////////////////////////////////////
//select_pro_spn = (Spinner) findViewById(R.id.selct_prject_spinner);
//datetextTextView = (TextView) findViewById(R.id.selctdate__txtv);
discription_list.add("Traffic light broken/not working");
discription_list.add("Traffic light pole hit by vehicle");
discription_list.add("No electricity connection");
discription_list.add("Traffic light not visible/partially visible");
// select_pro_spn.setOnItemSelectedListener(this);
// Creating adapter for spinner
des_dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, discription_list);
// Drop down layout style - list view with radio button
des_dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
// select_pro_spn.setAdapter(des_dataAdapter);
myCalendar = Calendar.getInstance();
date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
// datetextTextView.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// new DatePickerDialog(XenImageUploading.this, date, myCalendar
// .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
// myCalendar.get(Calendar.DAY_OF_MONTH)).show();
// }
// });
cameraclick.setOnClickListener(this);
galleryclick.setOnClickListener(this);
recyclerView.setOnClickListener(this);
}
private void updateLabel() {
String myFormat = "MM-dd-yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
datetextTextView.setText(sdf.format(myCalendar.getTime()));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
// case R.id.selct_prject_spinner:
// String selected_intersection = parent.getSelectedItem().toString();
// Log.e("Selected item ", selected_intersection);
// //parent.notifyAll();
// break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.camera_btn:
selectImage();
break;
case R.id.recycler_view:
getImageall();
break;
case R.id.gallery_btn:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i, SELECT_FILE);
break;
}
}
private void getImageall() {
}
private void selectImage() {
takepicture();
}
public void takepicture() {
Log.d(TAG, "takepicture");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
try {
photoFile_1 = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile_1 != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile_1));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && null != data) {
// Save Image To Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
////////////////setting image to adapter on capturing///////////////////////////
clickpath = mCurrentPhotoPath;
Bitmap bitmap = BitmapUtility.decodeSampledBitmapFromResource(clickpath, 560, 300);
setCameraDisplayOrientation(bitmap);
try {
FileOutputStream fos = new FileOutputStream(photoFile_1);
finalrotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
Data_Model data_model = new Data_Model();
data_model.setImage(finalrotatedBitmap);
image_view.setImageBitmap(finalrotatedBitmap);
arrayList.add(data_model);
m = new MyAdapter(this, arrayList);
recyclerView.setAdapter(m);
m.notifyDataSetChanged();
}
if (requestCode == SELECT_FILE && resultCode == RESULT_OK && null != data) {
InputStream stream = null;
Uri uri = data.getData();
//for (int i =0 ; i<numberOfImages ;i++){
getImagePath(uri);
Data_Model data_model = new Data_Model();
data_model.setImage(finalbitmap);
image_view.setImageBitmap(finalbitmap);
arrayList.add(data_model);
m = new MyAdapter(this, arrayList);
recyclerView.setAdapter(m);
m.notifyDataSetChanged();
// }
}
}
public String getImagePath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
finalbitmap = BitmapUtility.decodeSampledBitmapFromResource(path, 560, 300);
//targetImage = (ImageView)findViewById(R.id.imageView1);
image_view.setImageBitmap(finalbitmap);
return path;
}
public static void setCameraDisplayOrientation(Bitmap fileresult) {
Log.e(TAG, "setCameraDisplayOrientation");
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(clickpath, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(clickpath, opts);
ExifInterface exif = null;
try {
exif = new ExifInterface(clickpath);
} catch (IOException e) {
e.printStackTrace();
}
String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
int rotationAngle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;
Matrix matrix = new Matrix();
matrix.setRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
finalrotatedBitmap = AddTextonBitmap.textAsBitmap(rotatedBitmap, bitmap_overdraw_str);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
}
Adapter class
package www.welkinfort.com.pphc;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
/**
* Created by Admin on 13-Jul-17.
*/
class MyAdapter extends RecyclerView.Adapter<MyAdapter.Myviewholder> {
private static final String TAG = "Adapter";
static Data_Model m;
XenImageUploading xenImageUploading;
ArrayList<Data_Model> arrayList;
private Context mContext;
public MyAdapter(XenImageUploading xenImageUploading, ArrayList<Data_Model> arrayList) {
this.arrayList = arrayList;
this.xenImageUploading = xenImageUploading;
}
#Override
public Myviewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.abc, parent, false);
Myviewholder myviewholder = new Myviewholder(view);
Log.d("myactivty ", "oncreateViewHolder");
return myviewholder;
}
#Override
public void onBindViewHolder(final Myviewholder holder, final int position) {
m = arrayList.get(position);
Log.d(" myactivty", "onBindviewholder" + position);
holder.imageView.setImageBitmap(m.getImage());
}
#Override
public int getItemCount() {
return arrayList == null ? 0 : arrayList.size();
}
public class Myviewholder extends RecyclerView.ViewHolder {
// public View view;
public ImageView imageView;
public Myviewholder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
}
}
try this create one method in your adapter like this
public ArrayList<Data_Model> getArray() {
return arrayList;
}
now on your button click just call this method
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Data_Model> arrayList= adapter.getArray();
}
});
ask me in case of any query
I exercises have done in a simple list of tasks. Here's the code of my class TODOFragment
package pl.edu.ug.aib.studentizerApp.fragment;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import org.androidannotations.annotations.EFragment;
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.Fragment;
import pl.edu.ug.aib.studentizerApp.R;
import pl.edu.ug.aib.studentizerApp.todoList.DatabaseHandler;
import pl.edu.ug.aib.studentizerApp.todoList.Task;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#EFragment(R.layout.fragment_todo)
public class TODOFragment extends android.support.v4.app.Fragment {
EditText zadanieTxt, opisTxt, dataTxt, adresTxt;
List<Task> Tasks = new ArrayList<Task>();
ListView TaskListView;
DatabaseHandler dbHandler;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_todo, container, false);
}
#Override
public void onStart() {
super.onStart();
zadanieTxt = (EditText) getView().findViewById(R.id.txtZadanie);
opisTxt = (EditText) getView().findViewById(R.id.txtOpis);
dataTxt = (EditText) getView().findViewById(R.id.txtData);
adresTxt = (EditText) getView().findViewById(R.id.txtAdres);
TaskListView = (ListView) getView().findViewById(R.id.listView);
dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
TabHost tabHost = (TabHost) getView().findViewById(R.id.baner);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("Dodaj zadanie");
tabSpec.setContent(R.id.tabZadanie);
tabSpec.setIndicator("Dodaj Zadanie");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("lista");
tabSpec.setContent(R.id.tabListaZadan);
tabSpec.setIndicator("Lista");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) getView().findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Task task = new Task(dbHandler.getTaskCount(), String.valueOf(zadanieTxt.getText()), String.valueOf(opisTxt.getText()), String.valueOf(dataTxt.getText()), String.valueOf(adresTxt.getText()));
if (!taskExists(task)) {
dbHandler.createZadanie(task);
Tasks.add(task);
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " zostało dodane do listy zadań!", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " Zadanie już istnieje", Toast.LENGTH_SHORT).show();
}
});
zadanieTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
addBtn.setEnabled(String.valueOf(zadanieTxt.getText()).trim().length() > 0);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
if (dbHandler.getTaskCount() != 0)
Tasks.addAll(dbHandler.getAllTasks());
populateList();
}
private boolean taskExists(Task task) {
String zadanie = task.getZadanie();
int taskCount = Tasks.size();
for (int i = 0; i < taskCount; i++) {
if (zadanie.compareToIgnoreCase(Tasks.get(i).getZadanie()) == 0)
return true;
}
return false;
}
private void populateList() {
ArrayAdapter<Task> adapter = new TaskListAdapter();
TaskListView.setAdapter(adapter);
}
private class TaskListAdapter extends ArrayAdapter<Task> {
public TaskListAdapter()
{
super (TODOFragment.this.getActivity(), R.layout.listview_item, Tasks);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Task currentTask = Tasks.get(position);
TextView zadanie = (TextView) view.findViewById(R.id.zadanie);
zadanie.setText(currentTask.getZadanie());
TextView opis = (TextView) view.findViewById(R.id.opis);
opis.setText(currentTask.getOpis());
TextView data = (TextView) view.findViewById(R.id.data);
data.setText(currentTask.getData());
TextView adres = (TextView) view.findViewById(R.id.adres);
adres.setText(currentTask.getAdres());
return view;
}
}
}
And my DatabaseHandler
package pl.edu.ug.aib.studentizerApp.todoList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kisiel on 2015-06-02.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "ZadaniaManager",
TABLE_ZADANIA = "zadania",
KEY_ID = "id",
KEY_ZADANIE = "zadanie",
KEY_OPIS = "opis",
KEY_DATA = "data",
KEY_ADRES = "adres";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_ZADANIA + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ZADANIE + " TEXT," + KEY_OPIS + " TEXT," + KEY_DATA + " TEXT," + KEY_ADRES + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ZADANIA);
onCreate(db);
}
public void createZadanie(Task task) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ZADANIE, task.getZadanie());
values.put(KEY_OPIS, task.getOpis());
values.put(KEY_DATA, task.getData());
values.put(KEY_ADRES, task.getAdres());
db.insert(TABLE_ZADANIA, null, values);
db.close();
}
public Task getTask(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_ZADANIA, new String[] { KEY_ID, KEY_ZADANIE, KEY_OPIS, KEY_DATA, KEY_ADRES }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
Task task = new Task(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
db.close();
cursor.close();
return task;
}
public void deleteTask(Task task) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_ZADANIA, KEY_ID + "=?", new String[] { String.valueOf(task.getId()) });
db.close();
}
public int getTaskCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ZADANIA, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateTask(Task task) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ZADANIE, task.getZadanie());
values.put(KEY_OPIS, task.getOpis());
values.put(KEY_DATA, task.getData());
values.put(KEY_ADRES, task.getAdres());
int rowsAffected = db.update(TABLE_ZADANIA, values, KEY_ID + "=?", new String[] { String.valueOf(task.getId()) });
db.close();
return rowsAffected;
}
public List<Task> getAllTasks() {
List<Task> tasks = new ArrayList<Task>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_ZADANIA, null);
if (cursor.moveToFirst()) {
do {
tasks.add(new Task(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4)));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return tasks;
}
}
The problem is when you added a second task. The first has been added successfully, when you try to add another message appears:
Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " Zadanie już istnieje", Toast.LENGTH_SHORT).show();
I have a BaseAdapter class using ViewHolders to display a list of checked apps. I store the checked apps with SharedPreferences so the apps that are checked stay checked. What I am trying to achieve is getting the checked apps in my Service Class as ideally store it in an arraylist or something of the sort.
The problem is that the keys are what I used to the get the values are in the BaseAdapter class too and I can't get it from the service class so I had to recreate the methods for getting the list of packages and iterating through with a for loop.
I also cannot checked if the holder checkbox is checked in my Service class since that is done in my BaseAdapter class.
Despite passing the context in BaseAdapter and using getApplicationContext with SharedPreferences I cannot get the list of checked apps in the service class. I am not sure where to turn now. I have tried everything from messing around with static variables, trying everything with getting the context from the BaseAdapter class etc.
Here is my Adapter Class (I have commented where I get the apps which are checked):
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.ArrayList;
import java.util.List;
//
public class ApkAdapter extends BaseAdapter {
//Pastebin link: http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
// http://pastebin.com/Te2g072w, http://pastebin.com/NLT5iUiA ,
SharedPreferences sharedPrefs;
List<PackageInfo> packageList;
ArrayList <String> appchecklist;
static ArrayList <String> newappchecklist;
Context mContext;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
String PACKAGE_NAME;
static TinyDB appcheckdb;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.mContext = mContext;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
appchecklist = new ArrayList<String>();
newappchecklist = new ArrayList<String>();
appcheckdb = new TinyDB(context);
}
public ApkAdapter(Context heartBeat) {
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
TextView packageName;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
holder.packageName = (TextView) convertView.findViewById(R.id.app_package);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
final PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
// Make sure to define it again!
PACKAGE_NAME = packageInfo.packageName;
final String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 80, 80);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
//holder.packageName.setText(PACKAGE_NAME);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
for(int i= 0; i<packageList.size(); i++){
PACKAGE_NAME = packageInfo.packageName;
//Log.d("lol", PACKAGE_NAME);
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
newappchecklist = appcheckdb.getList("appcheck");
holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));
}
// appchecklist has all the checked apps!!!!!
// it is right here!!!!!!
if(holder.ck1.isChecked()){
appchecklist.add(packageInfo.packageName);
appcheckdb.putList("appcheck", appchecklist);
for (Object data : appchecklist) {
Log.e("HUH!?: ",(String) data);
}
}
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = context.getSharedPreferences(packageInfo.packageName, Context.MODE_PRIVATE).edit();
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
editor.putBoolean(packageInfo.packageName, true);
editor.apply();
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
/* editor.putBoolean(packageInfo.packageName, false);
editor.apply();*/
}
}
});
return convertView;
}
public void check( View convertView, int position){
final ViewHolder holder;
holder = new ViewHolder();
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
convertView.setTag(holder);
final PackageInfo packageInfo = (PackageInfo) getItem(position);
PACKAGE_NAME = packageInfo.packageName;
if(holder.ck1.isChecked()){
appchecklist.add(packageInfo.packageName);
appcheckdb.putList("appcheck", appchecklist);
for (Object data : appchecklist) {
Log.e("HUH!?: ",(String) data);
}
}
}
public static ArrayList getArrayList()
{
newappchecklist = appcheckdb.getList("appcheck");
return newappchecklist;
}
}
Here is my service class! I commented where I am trying to get the list:
package com.ibc.android.demo.appslist.app;
import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
public class HeartBeat extends Service {
private static final String TAG = HeartBeat.class.getSimpleName();
public Timer TIMER;
String CURRENT_PACKAGE_NAME;
private static Set<AccessGranted> mAccessGrantedList = new HashSet<AccessGranted>();
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
private BroadcastReceiver mAccessGrantedReceiver;
private File mLockedAppsFile;
private ArrayList newArrayList = null;
SharedPreferences sharedPrefs;
PackageManager pm = null;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, HeartBeat.class));
pm = getPackageManager();
List<PackageInfo> packageList = pm
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//TRYING TO GET IT OVER HERE!
for(int i = 0; i < packageList1.size(); i++) {
Log.e("hannnnnnn values ", packageList1.get(i)+ "");
sharedPrefs = getApplicationContext().getSharedPreferences(String.valueOf(packageList1.get(i)), Context.MODE_PRIVATE);
}
//TRYING TO CHECK IT OVER HERE!
Map<String, ?> allEntries = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.e("map values", entry.getKey() + ": " + entry.getValue().toString());
}
// Log.i("LocalService", "Received start id " + startId + ": " +
// intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
mAccessGrantedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String packageName = intent.getStringExtra("packageName");
if (action.equals(Constants.ACTION_GRANT_ACCESS) && packageName != null) {
AccessGranted ag = new AccessGranted(packageName);
mAccessGrantedList.remove(ag);
mAccessGrantedList.add(ag);
}
}
};
IntentFilter filter2 = new IntentFilter(Constants.ACTION_GRANT_ACCESS);
registerReceiver(mAccessGrantedReceiver, filter2);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, HeartBeat.class));
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
// Log.e("activity on Top", "" + activityOnTop);
// Log.e(" My package name", "" + getApplicationContext().getPackageName());
// newArrayList = ApkAdapter.getArrayList();
// for (Object data : newArrayList) {
// Provide the packagename(s) of apps here, you want to show password activity
if ((activityOnTop.contains("com.android.camera")) &&
(!activityOnTop.contains(getApplicationContext().getPackageName()
))) { // you have to make this check even better
Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra( "", "");
startActivity(i);
}
//}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
}
Ultimately, I can just tryna get the job done for getting a list of checked apps in my service class. So no matter what whenever I have the service running I have the list of checked apps. Whenever the app opens, re opens, restarts or does whatever, etc.
Help is appreciated. Let me know if there is anything else I can add.
I ended up creating a new database in my SharedPreferences to store only checked apps.
Here is my BaseAdapter class:
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.HashSet;
import java.util.List;
//
public class ApkAdapter extends BaseAdapter {
//Pastebin link: http://pastebin.com/LGRicg4U , http://pastebin.com/c4WfmhMK , http://pastebin.com/gFuuM4dY, http://pastebin.com/4Q7EP9G4
// http://pastebin.com/Te2g072w, http://pastebin.com/NLT5iUiA ,
SharedPreferences sharedPrefs;
SharedPreferences sharedPrefsapp;
List<PackageInfo> packageList;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
HashSet checked;
String PACKAGE_NAME;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
TextView packageName;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1= (CheckBox)convertView
.findViewById(R.id.checkBox1);
holder.packageName = (TextView) convertView.findViewById(R.id.app_package);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
final PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
// Make sure to define it again!
PACKAGE_NAME = packageInfo.packageName;
final String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 80, 80);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
//holder.packageName.setText(PACKAGE_NAME);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
// CHANGE UP EVERYTHING! MAKE THIS SHIT WORK, TIGGA!
checked = new HashSet();
PACKAGE_NAME = packageInfo.packageName;
//Log.d("just here: ", PACKAGE_NAME);
sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = context.getSharedPreferences("appdb", Context.MODE_PRIVATE);
holder.ck1.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME,false));
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE).edit();
SharedPreferences.Editor editorapp = context.getSharedPreferences("appdb", Context.MODE_PRIVATE).edit();
if (holder.ck1.isChecked()) {
itemChecked[position] = true;
holder.ck1.setChecked(true);
editor.putBoolean(packageInfo.packageName, true);
editorapp.putString(packageInfo.packageName, packageInfo.packageName);
editor.apply();
editorapp.apply();
// sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
} else {
itemChecked[position] = false;
holder.ck1.setChecked(false);
editor.putBoolean(packageInfo.packageName, false);
editorapp.remove(packageInfo.packageName);
editor.apply();
editorapp.apply();
//sharedPrefs = context.getSharedPreferences(context.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
}
}
});
return convertView;
}
}
I retrieve the values in service class with key "appdb"
package com.ibc.android.demo.appslist.app;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HeartBeat extends Service {
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//startService(new Intent(this, HeartBeat.class));
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
//Log.e("right key: ", entry.getKey() + "right value: " + entry.getValue().toString() );
packagezList.add(entry.getKey());
}
for(Object object: packagezList){
Log.e("YO!", (String) object);
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
// Log.e("activity on Top", "" + activityOnTop);
// Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
// Provide the packagename(s) of apps here, you want to show password activity
if ((activityOnTop.contains((CharSequence) object)) &&
(!activityOnTop.contains(getApplicationContext().getPackageName()
))) { // you have to make this check even better
Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra( "", "");
startActivity(i);
}
}
} catch (Exception e) {
// Log.e("Foreground App", e.getMessage(), e);
}
Intent ishintent = new Intent(this, HeartBeat.class);
PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),150000, pintent);
return START_STICKY;
}
// Log.i("LocalService", "Received start id " + startId + ": " +
// intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
#Override
public void onDestroy() {
Intent ishintent = new Intent(this, HeartBeat.class);
PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),150000, pintent);
//startService(new Intent(this, HeartBeat.class));
}
// this.stopSelf();
//startforeground goes here
}
I have a problem receiving data from my database. As determined in my codes, my database (TBL_MAHRIE) contains three columns (ID , COL_SAL , COL_NERKH). Running my project, I received repeated data in both of spinner and ListView.
Mahrie.java (MY SPINNER LOAD HERE)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Mahrie extends Activity {
private Spinner spinner_sal1, spinner_sal2;
private Button btn_calc;
EditText ed_shakhes_Nekah, ed_shakhes_Motalebe;
TextView tv_res;
float shakhes_Nekah, shakes_Motalebe, final_Res;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie);
ed_shakhes_Motalebe = (EditText) findViewById(R.id.ed_shakhes_Motalebe);
ed_shakhes_Nekah = (EditText) findViewById(R.id.ed_shakes_Nekah);
tv_res = (TextView) findViewById(R.id.tv_res);
// DATABASE
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("1392", "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("1391", "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("1390", "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("1389", "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("1388", "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("1387", "25");
databaseAdapter.insertShakhes(shakhes6);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
List<String> list = new ArrayList<String>();
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
List<Shakhes> data_shakhes = null;
data_shakhes = databaseAdapter.getAllShakhes();
Context context = getApplicationContext();
for (int i = 0; i < data_shakhes.size(); i++) {
list.add((data_shakhes.get(i).getSal()));
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_sal2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner_sal1 = (Spinner) findViewById(R.id.spinner_Sal1);
spinner_sal1
.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner_sal1 = (Spinner) this.findViewById(R.id.spinner_Sal1);
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
btn_calc = (Button) findViewById(R.id.btn_calc);
btn_calc.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shakhes_Nekah = Float.parseFloat(ed_shakhes_Nekah.getText()
.toString());
shakes_Motalebe = Float.parseFloat(ed_shakhes_Motalebe
.getText().toString());
final_Res = shakes_Motalebe / shakhes_Nekah;
tv_res.setText(final_Res + "");
}
});
}
}
2.DataBase Handler.java
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ToggleButton;
public class DataBaseHandler {
SQLiteDatabase database;
public DataBaseHandler(Context context) {
ShakhesDatabaseOpenHelper shakhesDatabaseOpenHelper = new ShakhesDatabaseOpenHelper(
context, "shakhsdb.db", null, 1);
database = shakhesDatabaseOpenHelper.getWritableDatabase();
}
public class ShakhesDatabaseOpenHelper extends SQLiteOpenHelper {
public ShakhesDatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
String query = "create table IF NOT EXISTS TBL_MAHRIE (ID INTEGER PRIMARY KEY, COL_SAL TEXT, COL_NERKH TEXT)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
}
}
public long insertShakhes(Shakhes shakhes) {
ContentValues values = new ContentValues();
values.put("COL_SAL", shakhes.getSal());
values.put("COL_NERKH", shakhes.getNerkh());
return database.insert("TBL_MAHRIE", null, values);
}
boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen()) {
return false;
}
Cursor cursor = db
.rawQuery(
"SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?",
new String[] { "table", tableName });
if (!cursor.moveToFirst()) {
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
Shakhes p = new Shakhes();
if (c.moveToFirst()) {
do {
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
Mahrie_JadvalActivity (My ListView inflate here)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Mahrie_JadvalActivity extends Activity {
ListView personListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie__jadval);
personListView = (ListView) findViewById(R.id.personListView);
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("2392" , "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("2391" , "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("2390" , "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("2389" , "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("2388" , "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("2387" , "25");
databaseAdapter.insertShakhes(shakhes6);
List<Shakhes> shakhes =
databaseAdapter.getAllShakhes() ;
ShakhesListViewAdapter shakhesListViewAdapter = new ShakhesListViewAdapter(this, R.layout.mahrie_list_view_item, shakhes);
personListView.setAdapter(shakhesListViewAdapter);
}
public class ShakhesListViewAdapter extends ArrayAdapter<Shakhes> {
List<Shakhes> data;
Context context;
public ShakhesListViewAdapter(Context context, int resourceId, List<Shakhes> data) {
super(context, resourceId, data);
this.data = data;
this.context = context;
}
#Override
public View getView(final int position, View item, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
item = inflater.inflate(R.layout.mahrie_list_view_item, parent , false);
TextView familyTextView = (TextView) item.findViewById(R.id.familyTextView);
familyTextView.setText(data.get(position).getSal()) ;
//familyTextView.setTypeface(bYekan);
TextView nameTextView = (TextView) item.findViewById(R.id.nameTextView);
nameTextView.setText(data.get(position).getNerkh()) ;
//nameTextView.setTypeface(bYekan);
Button detailsButton = (Button) item.findViewById(R.id.detailsButton);
detailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,
// data.get(position).getSal() + " " + data.get(position).getNerkh(),
// Toast.LENGTH_LONG).show();
Toast.makeText(context,
data.size()+"" + " and ID is " + position + "" ,
Toast.LENGTH_LONG).show();
}
});
//item.startAnimation(animation);
return item;
}
} }
4.Shakhes.java
package ir.dadpardaz.mahrie_dadpardaz;
public class Shakhes {
public int id ;
public static String sal ;
public static String nerkh ;
public Shakhes(int id, String sal, String nerkh) {
super();
this.id = id;
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes(String sal, String nerkh) {
super();
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getNerkh() {
return nerkh;
}
public void setNerkh(String nerkh) {
this.nerkh = nerkh;
}
}
Inside your DataBaseHandler.java , Make the following change
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
if (c.moveToFirst()) {
do {
Shakhes p = new Shakhes();
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
code the line Shakhes p = new Shakhes(); inside do-while loop. Otherwise it will overwrite the old one, and the same will be added in arraylist.