You must call removeView() on the child's parent first - android

The app is supposed to count the size of a loan payment and print the answer when button is pressed, but when I press the button it gives this: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here's the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical">
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/kokota"></EditText>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/prota"></EditText>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/lainata"></EditText>
<EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/maksuta"></EditText>
<Button android:layout_width="match_parent" android:text="Laske!" android:layout_height="70dip" android:id="#+id/btnClickMe"></Button>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/tasaera"></TextView>
</LinearLayout>
And the code:
package com.example.lainalaskuri;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class Lainalaskuri extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button)findViewById(R.id.btnClickMe);
btn1.setOnClickListener(btnListener);
}
double N, p, m, n, l, B;
public static double laskeTasaera(double p, double n, double m, double N) {
double A = (Math.pow(1 + p /(100 * m),n) * (p / (100* m))) /
(Math.pow(1 + p /(100*m), n) -1) * N;
return A;
}
private OnClickListener btnListener = new OnClickListener()
{
public void onClick(View v)
{
EditText kokota, prota, lainata, maksuta;
String koko, pro, laina, maksu;
kokota = (EditText)findViewById(R.id.kokota);
prota = (EditText)findViewById(R.id.prota);
lainata = (EditText)findViewById(R.id.lainata);
maksuta = (EditText)findViewById(R.id.maksuta);
koko = kokota.getText().toString();
int N = Integer.parseInt(koko);
pro = prota.getText().toString();
double p = Double.parseDouble(pro);
laina = lainata.getText().toString();
int l = Integer.parseInt(laina);
maksu = maksuta.getText().toString();
int m = Integer.parseInt(maksu);
n = l * m;
B = laskeTasaera(p, n, m, N);
TextView tasaera = (TextView) findViewById(R.id.tasaera);
tasaera.setText((B) + " €");
setContentView(tasaera);
}
};
}

The argument to setContentView is usually a layout XML file, rather than a View object, as you have here.
I would resolve this by breaking it down into a series of simpler steps. First, get all the Views you want on the screen, and in the right place.
Then write a handler for the button event - make it change the label on the button.
Finally add in the calculations.
Don't bite off more than you can chew - the secret of successful programming.

Related

is there a way to dynamicaly add a widget on top of another widget

i'm trying to create a widget called DecoView dynamicaly every time i press a button.
if i just put two deco views in the XML i can see them both and they both look fine on ontop of the other.
but when i try to add it dynamicly in the code, i only create the first one,
and all the rest just aren't get created
what am i missing here ?
can someone help me with this ?
my mainActivity.java
package com.example.shay_v.dynamicdecoviewexample;
import android.graphics.Color;
import android.graphics.PointF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.hookedonplay.decoviewlib.DecoView;
import com.hookedonplay.decoviewlib.charts.SeriesItem;
import com.hookedonplay.decoviewlib.events.DecoEvent;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button mainMenuButton;
int widgetInteger = 1;
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//pointing to display
mainMenuButton = (Button) findViewById(R.id.button);
mainMenuButton.setOnClickListener(this);
//points to the linear layout in the xml
ll = (LinearLayout)findViewById(R.id.mainMenu_mainLayout);
}
private void createDecoViewWidget (int i) {
//adds params to the linear layout
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//deco view widget
DecoView decoViewWidget = new DecoView(this);
//adding to view
decoViewWidget.setId(i);
ll.addView(decoViewWidget, params);
//decoViewWidget.configureAngles((int) (Math.random() * 360) + 1, (int) (Math.random() * 100));
//Create data series track
SeriesItem seriesItem = new SeriesItem.Builder(Color.argb(255, (int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255)))
//third controller is end point
.setRange(0, 100, 0)
.setLineWidth(60f)
.setInset(new PointF(120f, 120f))
.build();
int series1Index = decoViewWidget.addSeries(seriesItem);
decoViewWidget.addEvent(new DecoEvent.Builder((float) (Math.random() * 100)).setIndex(series1Index).setDelay(1000).build());
}
//button listener
#Override
public void onClick(View v) {
createDecoViewWidget (widgetInteger);
widgetInteger++;
}
}
my activity_main.xml >
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.shay_v.dynamicdecoviewexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<LinearLayout
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="350dp"
android:layout_centerVertical="true"
android:id="#+id/mainMenu_mainLayout"
android:layout_centerHorizontal="true"></LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
anyone ?
When you are creating the Views they are being added into a LinearLayout. This type of layout will position the views one after the other, so the second view is being drawn off the visible area of the screen.
As you want all views to be drawn on top of each other you should use a RelativeLayout.

OnClick Button action in Custom ListView

Actually, I was trying to implement a shopping cart using Android Studio. There is a custom list view in the main page included an "Add to Cart" button. So, whenever I click on the button the item must be added in the cart. But, I have no idea. Please guys, help me out. I'm a newbie.
Here is the Product Adapter
package com.example.raswap.octomatic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by aurora on 22/03/16.
*/
public class Pro_Adapter extends ArrayAdapter {
List list = new ArrayList();
public Pro_Adapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler{
ImageView img;
TextView p_name;
TextView b_name;
TextView price;
Button b_atc;
}
#Override
public void add(Object object) {
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.e_layout, parent, false);
handler = new DataHandler();
handler.img = (ImageView)row.findViewById(R.id.pro_image);
handler.p_name = (TextView)row.findViewById(R.id.pro_name);
handler.b_name = (TextView)row.findViewById(R.id.brand);
handler.price = (TextView)row.findViewById(R.id.pricing);
handler.b_atc = (Button)row.findViewById(R.id.atc);
row.setTag(handler);
}else{
handler = (DataHandler)row.getTag();
}
Product_data_provider dataProvider;
dataProvider = (Product_data_provider)this.getItem(position);
handler.img.setImageResource(dataProvider.getPro_img_resource());
handler.p_name.setText(dataProvider.getPro_name());
handler.b_name.setText(dataProvider.getBr_name());
handler.price.setText(dataProvider.getPricing());
return row;
}
}
Here is the Main Activity class:
package com.example.raswap.octomatic;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class E_shop extends Activity {
ListView listView;
int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
String[] pro_name;
String[] br_name;
String[] price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_e_shop);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
View z = findViewById(R.id.oct_logo);
z.setClickable(true);
z.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, MainActivity.class));
}
});
View x = findViewById(R.id.for_user_info);
x.setClickable(true);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(E_shop.this, UserInformation.class));
}
});
Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
ListView listView = (ListView)findViewById(R.id.e_list);
listView.setAdapter(adapter);
pro_name = getResources().getStringArray(R.array.nameOfProduct);
br_name = getResources().getStringArray(R.array.branding);
price = getResources().getStringArray(R.array.pricing);
int i = 0;
for(String pro: pro_name){
Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
adapter.add(dataProvider);
i++;
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
newActivity.putExtra("pro_emage",R.drawable.gb32);
newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
startActivity(newActivity);
break;
case 1:
Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
Activity1.putExtra("pro_emage",R.drawable.tb1);
Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
startActivity(Activity1);
break;
case 2:
Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
Activity2.putExtra("pro_emage", R.drawable.dvd);
Activity2.putExtra("title", "A pack of 50 DVD's");
Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
startActivity(Activity2);
break;
}
}
#SuppressWarnings("unused")
public void onClick(View v){
}
});
}
}
Here is the Product Data Provider Class:
package com.example.raswap.octomatic;
/**
* Created by aurora on 22/03/16.
*/
public class Product_data_provider {
private int pro_img_resource;
private String pro_name;
private String br_name;
private String pricing;
public int getPro_img_resource() {
return pro_img_resource;
}
public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
this.setPro_img_resource(pro_img_resource);
this.setPro_name(pro_name);
this.setBr_name(br_name);
this.setPricing(pricing);
}
public void setPro_img_resource(int pro_img_resource) {
this.pro_img_resource = pro_img_resource;
}
public String getPro_name() {
return pro_name;
}
public void setPro_name(String pro_name) {
this.pro_name = pro_name;
}
public String getBr_name() {
return br_name;
}
public void setBr_name(String br_name) {
this.br_name = br_name;
}
public String getPricing() {
return pricing;
}
public void setPricing(String pricing) {
this.pricing = pricing;
}
}
Now, Custom ListView XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/pro_image"
android:src="#drawable/gb32"
android:layout_width="160dp"
android:layout_height="match_parent" />
<LinearLayout
android:background="#afeeee"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Product Name"
android:id="#+id/pro_name"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Branding"
android:id="#+id/brand"
android:textColor="#000"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Price"
android:textColor="#000"
android:id="#+id/pricing"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:id="#+id/atc" />
</LinearLayout>
</LinearLayout>
<View
android:layout_below="#+id/oneL"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#000"/>
</RelativeLayout>
</RelativeLayout>
and finally the main layout XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.raswap.octomatic.E_shop">
<ListView
android:id="#+id/e_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Add your button's OnClick event in the Pro_Adapter's getView() methond as you do normally in your activities' onCreate() method.
Implement OnClickListener in your adapter class and get the Button click first and do the other task when you get the event. If you need the call back to your main activity class implement your own listener.follow the link enter link description here
Add the onClickListener to your Button in getView() of your ListAdapter.
If you want handle event click button in row, i'm think you should answer set button onclick event for every row of listview
you can try this.
Change in custom Listview xml file.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Cart"
android:onClick="AddCart"
android:id="#+id/atc" />
In MainActivity
public void AddCart(View v)
{
LinearLayout vwParentRow = (LinearLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(0);
child.setText("I've been clicked!");
vwParentRow.refreshDrawableState();
}

tab as like fileexploler

How can i put tab as like this at above..
i want this type of tab when i click item it show on above,can anyone give snippet or links..
and please tell brief if available how can i do this..
as show in figure the red rectangle is there any android tools for that or library....
or directly i can do by code??
Thanks in advance
Rectangle describe what i want
belove is image
..
I have made a simple project for you. You should make it more beautiful as I wasn't focusing on that, just on the code.
First add these values to your color.xml
<resources>
<color name="buttonGrey">#7A7A7A</color>
<color name="layoutHolderStartColor">#F7F7F7</color>
<color name="layoutHolderEndColor">#E1E1E1</color>
</resources>
Next create some background for the button holder and name it gradient_button_holder.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#color/layoutHolderStartColor"
android:endColor="#color/layoutHolderEndColor"
android:angle="270"
/>
<corners android:radius="3dp" />
</shape>
Now create activity_main.xml
Note: I am using some images, download the whole project at the bottom and get them out
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="#+id/pathHolder"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_alignParentTop="true"
android:background="#drawable/gradient_button_holder"
android:gravity="center_vertical">
<Button
android:id="#+id/btnAdd"
android:layout_width="29dp"
android:layout_height="29dp"
android:layout_alignParentRight="true"
android:layout_marginBottom="3dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:layout_marginTop="3dp"
android:background="#color/buttonGrey"
android:gravity="center"
android:onClick="onBtnAdd"
android:text="+"
android:textSize="15sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:src="#drawable/seperator"
android:visibility="gone"/>
<HorizontalScrollView
android:id="#+id/btnScrollView"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/btnAdd">
<LinearLayout
android:id="#+id/btnFolderHolder"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
</RelativeLayout>
Next create the Utils class
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
import java.util.concurrent.atomic.AtomicInteger;
public class Utils {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
/**
* Generate a value suitable for use in setId(int}.
* This value will not collide with ID values generated at build time by aapt for R.id.
*
* #return a generated ID value
*/
private static int generateViewId() {
for (; ; ) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) {
newValue = 1; // Roll over to 1, not 0.
}
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
#SuppressLint("NewApi")
public static int generateId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return generateViewId();
}
else {
return View.generateViewId();
}
}
}
And finally the MainActivity
import android.graphics.Color;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends ActionBarActivity {
private LinearLayout btnHolder;
private HorizontalScrollView scroller; //parent folders
private ViewTreeObserver observer; //needed for the scroll to the end
private Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
makeButtons(Environment.getExternalStorageDirectory().getPath(), "Folder1", "Folder2", "Folder3");
}
private void makeButtons(String... values) {
StringBuilder sb = new StringBuilder(values.length * 2);
for (int i = 0; i < values.length - 1; ++i) {
sb.append(values[i]);
sb.append(File.separator);
addButton(values[i], sb.toString(), true);
}
sb.append(values[values.length - 1]);
addButton(values[values.length - 1], sb.toString(), false);
}
private void init() {
setWidgetConnections();
observer = scroller.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
// this will always scroll to the last folder (displayed on the
// right)
scroller.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
}
});
}
private void setWidgetConnections() {
btnHolder = (LinearLayout) findViewById(R.id.btnFolderHolder);
scroller = (HorizontalScrollView) findViewById(R.id.btnScrollView);
}
public void onBtnAdd(View v) {
}
private void addButton(final String text, final String path, boolean withImage) {
// Dynamic call to add buttons
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(Utils.generateId());
btn.setText(text);
btn.setTextColor(Color.BLACK);
btn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToPath(path);
}
});
//btn.setBackgroundResource(R.drawable.gradient_button_holder);
btnHolder.addView(btn, params);
if (withImage) {
ImageView view = new ImageView(this);
view.setBackgroundResource(R.drawable.seperator2);
btnHolder.addView(view, params);
}
}
private void goToPath(String path) {
showToast(path);
}
private void showToast(String text) {
if (toast != null) {
toast.cancel();
}
toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
toast.show();
}
}
This is the final result and also note that it is horizontally scrollable
You can download the whole project here
It can be possible through your code,
In that Linear Layout you have to dynamically insert another layout having an image view represents the ">" and the text view used to reprsent the directory
the layout would be looks like that sort of
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/arrow_image"
android:text="Storage"/>
<ImageView
android:id="#+id/arrow_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:layout_alignParentLeft="true"
android:layout_alignBottom="#id/textView"
android:layout_alignTop="#id/textView"/>
</RelativeLayout>
While adding the View dynamically you just need to maintain the list of views added in account for clickevents, which would enables you to switch into the directories directly. And just remove that view from your view list as you move back to the previous directory, and that's all! you have made it.
and your code snippet will be look like this
final ArrayList<View> myDynamicView = new ArrayList<>();
//it would be your list item click
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View dynamicView = inflater.inflate(R.layout.field_layout, null);
dynamicView.setId(unique_id); // create a unique id to refer a view
TextView directoryName = (TextView) view.findViewById(R.id.textView);
directoryName.setText(your_directory_name);//Either fetch it through your array or by extracting the view
myDynamicView.add(myDynamicView.size(), dynamicView);
linearLayout.addView(dynamicView);
dynamicView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i= 0; i < myDynamicView.size(); i++){
//When view is clicked match the view id from the view list
if(myDynamicView.get(i).getId() == v.getId()){
//when view id got matched it means remove those view which are ahead of it
//from the list as well as from the linear layout
for(int j = i; j < myDynamicView.size(); j++){
View view = myDynamicView.get(j);
linearLayout.removeView(view);
myDynamicView.remove(j);
}
//update list
}
}
}
});
//update your list
}
});
This actually is done using Creating Swipe Views and updating the divider of tabs, or you can even customize the implementation by using HorizontalScrollView and adding a child when going in a folder and removing last child when going back.

Android application stopped working-Eclipse

I'm trying to develop an Android application that will solve some math functions according to the code. But when I save it, then run on emulator and when the emulator is launched it says me The application has stopped working.
Java Code;
package com.example.fibonacci;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button btn1;
TextView tv1;
EditText edt1;
String msj= "d";
double n = Double.valueOf(edt1 . getText().toString());
double a = (1 / (Math.sqrt(5)));
double b = ((1+(Math.sqrt(5)))/2);
double c = ((1-(Math.sqrt(5)))/2);
double i = a * ((Math.pow(b,n)) - (Math.pow(c,n)));
String k = String.valueOf(i);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
tv1 = (TextView) findViewById(R.id.tv1);
edt1= (EditText) findViewById(R.id.edt1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Click kodu buraya yazılacak
msj = edt1.getText().toString();
tv1.setText( k );
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.fibonacci.MainActivity" >
<EditText
android:id="#+id/edt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="number to cal."
android:inputType="number" >
</EditText>
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/edt1"
android:layout_below="#+id/edt1"
android:layout_marginTop="18dp"
android:text="button" />
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignLeft="#+id/btn1"
android:layout_below="#+id/btn1"
android:layout_marginTop="72dp"
android:text="result" />
double n = Double.valueOf(edt1 . getText().toString());
is outside of a method which means it runs before onCreate() which means your EditText is null. That can't be run until you initialize your EditText (i.e. must be after edt1= (EditText) findViewById(R.id.edt1);)
You are going to run into problems then with those calculations trying to run before onCreate(). Put them in a method and call them when you need to.
In the future, please provide the logcat with your post when your app crashes.
You initialize the n with the edit text's value, but your edit text object is null yet.
double n = Double.valueOf(edt1 . getText().toString());
Initialize after
edt1= (EditText) findViewById(R.id.edt1);

Resource not found TextView

I am taking my first steps in Android and am starting with a very simple app which keeps track of progress through a knitting pattern and shows the instructions for the relevant row.
I want to update a couple of TextView objects programmatically. However, using getViewById() does not seem to identify them properly and the app crashes.
Having searched on Google it seems there are sometimes problems with the XML namespace in the layout XML but mine looks OK. Is it something to do with scope, perhaps?
instructions.java (this is the only activity)
package uk.co.oketchup.blanketsquare;
import android.app.Activity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.view.View;
public class instructions extends Activity
{
private int mRow;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/* retrieve row from shared preferences, or start from zero if nothing there */
SharedPreferences settings = getPreferences(MODE_PRIVATE);
mRow = settings.getInt("row",0);
setContentView(R.layout.main);
/* associate onClick listeners with the two buttons */
final Button btnIncrement = (Button) findViewById(R.id.increment);
btnIncrement.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Increment row
++mRow;
calcAndUpdate();
}
});
final Button btnDecrement = (Button) findViewById(R.id.decrement);
btnDecrement.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Decrement row
--mRow;
calcAndUpdate();
}
});
}
private void calcAndUpdate() {
String Instructions;
int knit1;
int knit2;
int remaining;
if (mRow%2 == 1 )
{
/* Odd row */
knit1 = 40 - mRow;
Instructions = "K" + knit1;
remaining = knit1;
}
else
{
/* Even row */
knit1 = 18 - mRow/2;
knit2 = knit1 + 1;
Instructions = "Sl 1, k" + knit1 + ", [sl 1 kwise] 2 times, k1, p2sso, k" + knit2;
remaining = knit1 + knit2 + 2;
}
/* Update the display */
TextView tRow = (TextView) findViewById(R.id.row);
TextView tInstr = (TextView) findViewById(R.id.instr);
TextView tStRem = (TextView) findViewById(R.id.stitchremain);
/* Set the text */
tRow.setText(mRow);
tInstr.setText(Instructions);
tStRem.setText(remaining);
}
}
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/row"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Row"
/>
<TextView
android:id="#+id/instr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Instructions"
android:layout_below="#id/row"
/>
<Button
android:id="#+id/increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_alignParentBottom="true" />
<Button
android:id="#+id/decrement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:layout_toRightOf="#id/increment"
android:layout_alignParentBottom="true" />
<TextView
android:id="#+id/stitchremain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="stitches remaining"
android:layout_above="#id/increment"
/>
</RelativeLayout>
The TextView objects seem to have been registered ok as they appear in R.java
public static final class id {
public static final int decrement=0x7f050003;
public static final int increment=0x7f050002;
public static final int instr=0x7f050001;
public static final int row=0x7f050000;
public static final int stitchremain=0x7f050004;
}
Here is the error message shown in ddms.
Uncaught handler: thread main exiting due to uncaught exception
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:200)
at android.widget.TextView.setText(TextView.java:2813)
at uk.co.oketchup.blanketsquare.instructions.calcAndUpdate(instructions.java:75)
at uk.co.oketchup.blanketsquare.instructions.access$100(instructions.java:11)
at uk.co.oketchup.blanketsquare.instructions$1.onClick(instructions.java:33)
[etc]
Many thanks for your help.
mRow is an integer. When you call setText(mRow) on line 75, it thinks that you are trying to set the text with a String resource with ID = the value of mRow.
Instead, do:
tRow.setText(Integer.toString(mRow));
You should always convert other values to string before setting it to textview, like
txtX.setText(Integer.toString(intVal));

Categories

Resources