I'm trying to create a widget that will show the icon's of some app's installed on the device.
I manage to get a list of packages installed in the device, but i don't know how to get the icon from these.
I have this in my activity:
Code:
final static List<String> pacote_app = new ArrayList<String>();
final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
for (ApplicationInfo app : apps) {
//checks for flags; if flagged, check if updated system app
if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
// installedApps.add(app);
//it's a system app, not interested
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//Discard this one
//in this case, it should be a user-installed app
} else {
String pacote = (String) app.packageName; //NOME DOS PACOTES
pacote_app.add(pacote);
}
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
WidgetViewsFactory
Code:
import static com.example.magcr23.mywidget.LoremActivity.pacote_app;
public class WidgetViewsFactory implements RemoteViewsService.RemoteViewsFactory {
Context context;
private Context ctxt=null;
private int appWidgetId;
public WidgetViewsFactory(Context ctxt, Intent intent) {
this.ctxt=ctxt;
appWidgetId=intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
@Override
public void onCreate() {}
@Override
public void onDestroy() {
// no-op
}
@Override
public int getCount() {
return(pacote_app.size());
}
@Override
public RemoteViews getViewAt(int position) {
RemoteViews row=new RemoteViews(ctxt.getPackageName(),
R.layout.list_item);
//FILL LIST
row.setTextViewText(android.R.id.text1, pacote_app.get(position));
//SEND WORD TO ACTIVITY
Intent i=new Intent();
Bundle extras=new Bundle();
extras.putString(WidgetProvider.EXTRA_WORD, pacote_app.get(position));
i.putExtras(extras);
row.setOnClickFillInIntent(android.R.id.text1, i);
//--------------
return(row);
}
@Override
public RemoteViews getLoadingView() {
return(null);
}
@Override
public int getViewTypeCount() {
return(1);
}
@Override
public long getItemId(int position) {
return(position);
}
@Override
public boolean hasStableIds() {
return(true);
}
@Override
public void onDataSetChanged() {
// no-op
}
}
WidgetProvider
Code:
public class WidgetProvider extends AppWidgetProvider{
public static String EXTRA_WORD=
"com.commonsware.android.appwidget.lorem.WORD";
@Override
public void onUpdate(Context ctxt, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int i=0; i<appWidgetIds.length; i++) {
Intent svcIntent=new Intent(ctxt, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget=new RemoteViews(ctxt.getPackageName(),
R.layout.novo_widget);
widget.setRemoteAdapter(appWidgetIds[i], R.id.listagem,
svcIntent);
Intent clickIntent=new Intent(ctxt, LoremActivity.class);
PendingIntent clickPI=PendingIntent
.getActivity(ctxt, 0,
clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
widget.setPendingIntentTemplate(R.id.listagem, clickPI);
appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
}
super.onUpdate(ctxt, appWidgetManager, appWidgetIds);
}
}
WidgetService
Code:
public class WidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return(new WidgetViewsFactory(this.getApplicationContext(),
intent));
}
Layout
Code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/widget_margin"
android:orientation="horizontal">
<ListView
android:id="@+id/listagem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
ListView Layout
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
android:textColor="#000"
/>
</LinearLayout>
(Whoops, topic a bit old, haven't see the date)
Hi,
You should give a look to PackageItemInfo methods, especially loadIcon (https://developer.android.com/refer...ml#loadIcon(android.content.pm.PackageManager)
In your code:
Code:
final static List<String> pacote_app = new ArrayList<String>();
final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
for (ApplicationInfo app : apps) {
//checks for flags; if flagged, check if updated system app
if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
// installedApps.add(app);
//it's a system app, not interested
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
//Discard this one
//in this case, it should be a user-installed app
} else {
String pacote = (String) app.packageName; //NOME DOS PACOTES
pacote_app.add(pacote);
// I guess you want to get your icon here
Drawable packageIcon = app.loadIcon(pm);
}
}
To show it, the easiest might be to add an ImageView and call setImageDrawable
Good luck!
Related
I want to write a text file. But I am not sure how writing down works in Android. Here is my code:
Code:
EditText textbox1 = (EditText) findViewById(R.id.editText);
EditText textbox2 = (EditText) findViewById(R.id.editText2);
EditText textbox3 = (EditText) findViewById(R.id.editText3);
public void writeToPhonebook(View v) {
Button button=(Button) v;
try {
File fajl = new File("phonebook.txt");
Writer writer;
writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fajl, true), "UTF-8"));
writer.append(textbox1.getText() + "\t" + textbox2.getText() + "\t" + textbox3.getText());
writer.write("\r\n");
writer.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
}
catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
can I just leave phonebook.txt or need to put something else? Because with this code apk can't even start on emulator.
OK I done this previus. I now need to load data from text file into table (table layout with 3 columns). Is it possible for application to determine number of needed rows without me adding certain number. Because that data will be changed.
You need permissions to write a file, you set them in the AndroidManifest xml (Every Android Studio project has their own manifest, set it in your project)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Then you need to open a file for input/output... You do this in whatever.java
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.util.Log;
public class FileOperations {
public FileOperations() {
}
public Boolean write(String fname, String fcontent){
try {
String fpath = "/sdcard/"+fname+".txt";
File file = new File(fpath);
// If file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();
Log.d("Suceess","Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String read(String fname){
BufferedReader br = null;
String response = null;
try {
StringBuffer output = new StringBuffer();
String fpath = "/sdcard/"+fname+".txt";
br = new BufferedReader(new FileReader(fpath));
String line = "";
while ((line = br.readLine()) != null) {
output.append(line +"n");
}
response = output.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return response;
}
}
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Scrollview
Grimspiller said:
What is easier to display data from text file in: TableLayout or ViewList? If not sure total number of rows? Is there something for scrooling through it if can't fit the screen?
Click to expand...
Click to collapse
1) Yes. Android provide scrollview to scroll on your query.
A. Horizontal scrollview
B. Vertical Scrollview.
Also you can you onTextwatcher() to check if the field size increase , onAfterTextchanged() method you can resize the box is.
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.setVisibility(View.VISIBLE);
}
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
textView.setVisibility(View.GONE);
} else{
textView.setText("You have entered : " + passwordEditText.getText());
}
}
};
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Dynamic Data
Grimspiller said:
I found this tutorial for multicolumn ListView on techlovejump.com ,but data for it is hardcoded. I am not sure is it suitable for dynamic data adding from text file.
Click to expand...
Click to collapse
hey, As you see on after afterTextChanged(Editable s)
You can again call your table structure code to design it as per size.
I think you should try it once.
Share some amount of code if you find it difficult. I will help you afterTextChanged(Editable s).
I don't need to write text but to read it. Can you look at this code and tell me what is the problem? It can't find the file.
Code:
void showData(){
File fajl = new File("phonebook.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(fajl));
String line;
try {
while ((line = br.readLine()) != null) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
TextView im = new TextView(this);
im.setText(line);
im.setTextColor(Color.BLACK);
im.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
tr.addView(im);
tablel.addView(tr, new TableLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
button2.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
showData();
}
});
I have added to xml TableLayout and one row as header.
I use this for writing to text file:
Code:
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
try {
FileOutputStream fos = openFileOutput("phonebook.txt", Context.MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(textbox1.getText().toString() + "\t" + textbox2.getText().toString() + "\t" + textbox3.getText().toString());
osw.write("\r\n");
osw.close();
textbox1.setText("");
textbox2.setText("");
textbox3.setText("");
textbox1.requestFocus();
} catch (IOException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
});
Debbuger says it's writting file and lines just fine. But why I can't read it?
It creates "files" folder inside my app folder. And inside files it is phonebook.txt.
Hello,
I'm trying to create an app with some tabs that link to different activities, I was able to do that with tabhost and normal buttons with onClick=startActivity, but I had some problems losing the scrollbar position from tabs on every activity change.
Well, now I was reading about fragments, and its really interesting. i created the app with the codes below, I can click in every tab and I can see the content (just watched one tutorial with that), but I cant figure out how could I open one different activity in the FrameLayout when I click in each tab. I see that the code gets the tabs id and then uses it to create one text, what I cant figure out is how to verify if the ID is "X", it would open the "activity2", "....3", "....4", "...n". I tried to put some IFs inside it, but nothing worked.
Is there a way to do that ? This an ideal way of doing that or should I change something to make it easier and better ?
activity_main.xml
Code:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/horizontalScrollView"
android:scrollbars="none"
android:scrollbarSize="0dp">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
MainActivity.java
Code:
package com.example.tbarata.myapplication;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class MainActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("Tab 1111", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("Tab 2222", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("Tab 3333", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab44").setIndicator("Tab 44", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab5").setIndicator("Tab 55", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab6").setIndicator("Tab 66", null),
FragmentTab.class, null);
}
}
activity_fragment_layout.xml
Code:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#eaecee">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
FragmentTab.java
Code:
package com.example.tbarata.myapplication;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTab extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_fragment_layout, container, false);
TextView tv = (TextView) v.findViewById(R.id.text);
tv.setText(this.getTag() + " Content");
return v;
}
}
Thanks very much!
barata
Plz, could anyone give me some light, or just some link of a tutorial ? Could be even in japanese
I was able to load one activity here comparing the tab id and loading the activity, but when I did that, the tabHost was deleted, so I repeat all the tabHost lines in this second activity, and I can see when I click in its tab its loaded, but the app crashes
Here is the code I've changed:
fragmentTab.java - Just to check the tab id and then load the activity, with only this worked great, but no tabs in the second activity
Code:
if (this.getTag() == "tab2") {
Intent intent = new Intent(getActivity(), fragment_layout2.class);
startActivity(intent);
}
} else {
TextView tv = (TextView) v.findViewById(R.id.text);
tv.setText(this.getTag() + " Content");
}
So in the fragment_layout2.java I repeated the codes to show the tabs, but when I click in this tab2 the app crashes:
Code:
public class fragment_layout2 extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_layout2);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("Tab 1111", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("Tab 2222", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("Tab 3333", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab44").setIndicator("Tab 44", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab5").setIndicator("Tab 55", null),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab6").setIndicator("Tab 66", null),
FragmentTab.class, null);
}
Thanks.
Barata
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;
}
}
Hey guys.
So, I've spent the last two days watching every tutorial about working with sqlite, but I'm doing something wrong and can't find out what.
The app is done, only needs the SQLite part, Its basicly a webapp with favorites.
Altough I have changed the code several times, this is what I ended up with:
DBManager.java
<code>
package com.rjpf.mywebapps;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager
{
private DbHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c)
{
context=c;
}
public DBManager open() throws SQLException
{
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void insert(String name, String url)
{
ContentValues contentValue = new ContentValues();
contentValue.put(DbHelper.CONTACTS_COLUMN_NAME, name);
contentValue.put(DbHelper.CONTACTS_COLUMN_URL, url);
database.insert(dbHelper.CONTACTS_TABLE_NAME, null, contentValue);
}
}
</code>
When I try to call it in the main activity with:
MainActivity.java
<code>
(...)
private LinearLayout Layout_Add;
private TextView TxT_add_nomE;
private TextView TxT_add_urL;
private Button Button_Add_to_DB;
private Button btn_BACK_Add;
DbHelper myDB;
(...)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new DbHelper(this);
(...)
Button_Add_to_DB.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Add_ItemToDb();
}
});
(...)
public void Add_ItemToDb()
{
if (TxT_add_nomE.getText().toString().trim().length() == 0 || TxT_add_urL.getText().toString().trim().length() == 0)
{
TxT_add_nomE.setText("Please don't leave fields empty!");
return;
}
else
{
String addNome = TxT_add_nomE.getText().toString();
String addUrl = TxT_add_urL.getText().toString();
// ADD TO DB
DBManager DataManager = new DBManager(this);
DataManager.insert(addNome,addUrl); // This line is what gives the error, when I click the button to add the App craches
TxT_add_nomE.setText("Name");
TxT_add_urL.setText("Url");
}
}
</code>
Thanks in advance and sorry for the long post, This is my first app and also the first time in java