write multiple strings to a file and add a new line - android

I'm building a basic app that you choose from a spinner, select a color and click save. If the color you're looking for isn't in the spinner, you press a button and you can type it in to the EditText.
I'm trying to make it so I can write both the chosen spinner/edittext color and the date inside of the "colors.txt" file. at the moment, there are no errors but when i launch the app on my android it instantly crashes.
Colorchooser.java
package com.example.scalendar;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class Colorchooser extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colorchooser);
}
public void writetoFile(String str) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("colors.txt", Context.MODE_PRIVATE));
outputStreamWriter.write("colorstring , datestring");
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.colorchooser, menu);
return true;
}
}`
And here is my Strings.XML file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SCalendar</string>
<string name="action_settings">Settings</string>
<string name="color_prompt">What was todays color?</string>
<string name="SaveButtonText">Save To Calendar</string>
<string name="textfieldhint">Enter color</string>
<string name="otherbuttontext">Color not listed</string>
<string name="othercolorexplanationtext">Dont see the color here? Click the button below and type it yourself.</string>
<string-array name="color_arrays">
<item>Select a color:</item>
<item>Purple</item>
<item>Orange</item>
<item>Green</item>
<item>Red</item>
<item>Blue</item>
<item>Pink</item>
<item>Brown</item>
<item>Yellow</item>
<item>Black</item>
<item>White</item>
</string-array>
<string name="colorstring">
colorSpinner = findViewById(R.id.colorSpinner)
colorSpinner.getSelectedItem().toString()
</string>
<string name="datestring">
SimpleDateFormat formatter = new SimpleDateFormat("dd_MM_yyyy");
Date now = new Date();
String fileName = formatter.format(now).toString();
</string>
</resources>`
And here's my Mainactivity.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="Colorchooser" >
<Spinner
android:id="#+id/colorSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:entries="#array/color_arrays"
android:prompt="#string/color_prompt" />
<TextView
android:id="#+id/othercolorexplaination"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/colorSpinner"
android:layout_below="#+id/colorSpinner"
android:layout_marginTop="15dp"
android:text="#string/othercolorexplanationtext"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/ButtonSave"
style="#style/AppTheme"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/othercolorexplaination"
android:layout_alignParentBottom="true"
android:layout_marginBottom="62dp"
android:onClick="writetoFile(String getcolor)"
android:text="#string/SaveButtonText" />
<EditText
android:id="#+id/othercolor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ButtonSave"
android:layout_below="#+id/otherbutton"
android:layout_marginTop="42dp"
android:ems="10"
android:focusable="false"
android:hint="#string/textfieldhint"
android:inputType="textEmailAddress" >
</EditText>
<Button
android:id="#+id/otherbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/othercolorexplaination"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:onClick="othercolor.focusableInTouchMode(true)"
android:text="#string/otherbuttontext" />
</RelativeLayout>`

It seems you have some major misunderstandings on the relation between Java strings vs string variables, and string variables vs string resources:
This:
outputStreamWriter.write("colorstring , datestring");
Will always write "colorstring, datestring" to your file, so the file will look like:
colorstring, datestring
colorstring, datestring
colorstring, datestring
You cannot expect Java code in your string resources to be executed:
<string name="colorstring">
colorSpinner = findViewById(R.id.colorSpinner)
colorSpinner.getSelectedItem().toString()
</string>
Strings in your resources are Constants. There is no way to change them at run time.

Related

Android Search not accurate in passing another activity

Android Search is not accurate when passing another activity .
This is my app
This the main page
[Main] https://drive.google.com/open?id=0B2SE2JZYuezja2JqRHcycWdhWTA
When I search of a word the first array description will be display and it is not accurate description .
This is the same output to the one that I click
[Same output]https://drive.google.com/open?id=0B2SE2JZYuezjQmNFSm45RHloT3c
This is my codes
MainActivity.java
package com.skholingua.android.searchview;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater.Filter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener {
String[] stateList;
String[] anotherStringArray;
private SearchView searchView;
private ListView listView;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchView = (SearchView) findViewById(R.id.searchView1);
listView = (ListView) findViewById(R.id.listView1);
stateList = getResources().getStringArray(R.array.stateList);
anotherStringArray = getResources().getStringArray(R.array.anotherStringArray);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, stateList);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
// Sets the default or resting state of the search field.
// If true, a single search icon is shown by default and
// expands to show the text field and other buttons when pressed
//searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
// Sets the hint text to display in the query text field
//searchView.setQueryHint("State Name");
int searchPlateId = searchView.getContext().getResources()
.getIdentifier("android:id/search_plate", null, null);
View searchPlateView = searchView.findViewById(searchPlateId);
if (searchPlateView != null) {
searchPlateView.setBackgroundColor(Color.TRANSPARENT);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stateName = listView.getAdapter().getItem(position).toString();
// Put selected state to intent.
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("selectedState", stateName);
intent.putExtra("anotherStringArray",anotherStringArray[position]);
startActivity(intent);
}
});
}
#Override
public boolean onQueryTextChange(String newText) {
android.widget.Filter filter = adapter.getFilter();
if (TextUtils.isEmpty(newText)) {
filter.filter("");
} else {
filter.filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity.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"
android:focusableInTouchMode="true"
tools:context="com.skholingua.android.searchview.MainActivity" >
<SearchView
android:id="#+id/searchView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:background="#drawable/search_view_border"
android:iconifiedByDefault="false"
android:padding="2dp"
android:queryHint="Search...."
android:layout_alignParentTop="true" >
</SearchView>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView1"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
NextActivity.class
package com.skholingua.android.searchview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class NextActivity extends Activity {
TextView t1,t2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
t1 = (TextView) findViewById(R.id.name1);
t2 = (TextView) findViewById(R.id.name2);
Intent intent = getIntent();
String state_name= getIntent().getExtras().getString("selectedState");
String stateDescription= getIntent().getExtras().getString("anotherStringArray");
t1.setText(state_name);
t2.setText(stateDescription);
}
}
next.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:background="#00ffff"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Word:"
android:typeface="serif"
android:textColor="#000"
android:textSize="19dp" />
<TextView
android:id="#+id/name1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text=""
android:textColor="#f00"
android:textSize="18dp"
android:typeface="serif" />
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textColor="#000"
android:typeface="serif"
android:text="Definition:"
android:textSize="19dp" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/name2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#000"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:text=""
android:background="#fff"
android:textAppearance="?android:attr/textAppearanceMedium" />
</ScrollView>
</LinearLayout>
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SearchView</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="stateList">
<item>Abstract Window Toolkit (AWT)</item>
<item>abstract</item>
<item>abstract class</item>
<item>abstract method</item>
<item>access control</item>
<item>ACID</item>
<item>activation</item>
<item>actual parameter list</item>
<item>alpha value</item>
</string-array>
<string-array name="anotherStringArray">
<item>A collection of graphical user interface (GUI) components that were implemented usingnative-platform versions of the components. These components provide that subset of functionalitywhich is common to all native platforms. Largely supplanted by the Project Swing component set.</item>
<item>A Java(TM) programming language keyword used in a class definition to specify that a class is not to be instantiated, but rather inherited by other classes. An abstract class can have abstract method that are not implemented in the abstract class, but in subclasses.</item>
<item>A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.</item>
<item>A method that has no implementation.</item>
<item>The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.</item>
<item>The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation,and durability.</item>
<item>The process of transferring an enterprise bean from secondary storage to memory.</item>
</string-array>
</resources>
I hope you will help me to fix this problem . Thank you.
Here is your solution.
First replace your main activity listView.setOnItemClickListener=> onItemClick method with below code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String stateName = listView.getAdapter().getItem(position).toString();
int pos=0;
for(int i=0;i<stateList.length;i++)
{
if(stateList[i].equals(stateName))
{
pos=i;
break;
}
}
// Put selected state to intent.
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("selectedState", stateName);
intent.putExtra("anotherStringArray", anotherStringArray[pos]);
startActivity(intent);
}
});
And also make your stateList array and and anotherStringArray as same size in string.xml file.
<string-array name="stateList">
<item>Abstract Window Toolkit (AWT)</item>
<item>abstract</item>
<item>abstract class</item>
<item>abstract method</item>
<item>access control</item>
<item>ACID</item>
<item>activation</item>
<item>actual parameter list</item>
<item>alpha value</item>
</string-array>
<string-array name="anotherStringArray">
<item>A collection of graphical user interface (GUI) components that were implemented usingnative-platform versions of the components. These components provide that subset of functionalitywhich is common to all native platforms. Largely supplanted by the Project Swing component set.</item>
<item>A Java(TM) programming language keyword used in a class definition to specify that a class is not to be instantiated, but rather inherited by other classes. An abstract class can have abstract method that are not implemented in the abstract class, but in subclasses.</item>
<item>A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.</item>
<item>A method that has no implementation.</item>
<item>The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.</item>
<item>The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation,and durability.</item>
<item>The process of transferring an enterprise bean from secondary storage to memory.</item>
<item>Add your text here</item>
<item>Add some other text here</item>
</string-array>

getSelectedItemPosition android

I have been racking my brain trying to figure out why this won't work. I need to return the index of a selected item in a spinner (4 spinners actually but can't even get one to work).
Here is the 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.agcinstruments.lab41.MainActivity"
android:background="#color/Navy">
<ImageView
android:id="#+id/resistor2"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="#drawable/resistor2"/>
<TextView
android:background="#color/Navy"
android:layout_marginTop="36dp"
android:layout_marginLeft="120dp"
android:layout_width="25dp"
android:layout_height="73dp"
/>
<TextView
android:background="#color/Navy"
android:layout_marginTop="36dp"
android:layout_centerHorizontal="true"
android:layout_width="25dp"
android:layout_height="73dp"
/>
<TextView
android:id="#+id/q"
android:background="#color/Navy"
android:layout_marginTop="36dp"
android:layout_marginLeft="208dp"
android:layout_width="25dp"
android:layout_height="73dp"
/>
<TextView
android:background="#color/Navy"
android:layout_marginTop="26dp"
android:layout_marginLeft="257dp"
android:layout_width="25dp"
android:layout_height="94dp"
/>
<Spinner
android:id="#+id/Spinner1"
android:layout_below="#+id/resistor2"
android:layout_width="85dp"
android:entries="#array/color_array1"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Spinner
android:id="#+id/Spinner2"
android:layout_below="#id/resistor2"
android:layout_toRightOf="#+id/Spinner1"
android:layout_width="85dp"
android:entries="#array/color_array2"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Spinner
android:id="#+id/Spinner3"
android:layout_below="#id/resistor2"
android:layout_toRightOf="#+id/Spinner2"
android:layout_width="85dp"
android:entries="#array/color_array3"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Spinner
android:id="#+id/Spinner4"
android:layout_below="#id/resistor2"
android:layout_toRightOf="#+id/Spinner3"
android:layout_width="85dp"
android:entries="#array/color_array4"
android:layout_height="wrap_content"
android:background="#color/White"/>
<Button
android:id="#+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Spinner4"
android:layout_centerHorizontal="true"
android:text="#string/calculate"
android:onClick="onClickCalculate"/>
<TextView
android:id="#+id/resultText"
android:layout_width="50dp"
android:layout_height="50dp"
android:textColor="#color/Red"
android:layout_below="#+id/calculate"
android:layout_centerHorizontal="true"
android:background="#color/White" />
<EditText
android:id="#+id/tolerance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/Red"/>
<EditText
android:id="#+id/ohm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/Red"/>
</RelativeLayout>
And here is the java code
package com.agcinstruments.lab41;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.server.converter.StringToIntConverter;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public Spinner Spinner1;
public Spinner Spinner2;
public Spinner Spinner3;
public Spinner Spinner4;
int value = 0 ;
int position = 0 ;
TextView resultText;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = (TextView) findViewById(R.id.resultText);
// 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();
}
public void onClickCalculate(View view) {
position = Spinner2.getSelectedItemPosition(); // This is the problem.I suspect the adaptor is not working.
value = position * 10;
resultText.setText(Integer.toString(value));
//resultText.setBackgroundColor()
}
public void resistorValue2(View view) {
value = value + (1);
}
public void resistorMultiplier(View view) {
value = value + (1);
}
public void resistorTolerance(View view) {
value = value + (1);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.agcinstruments.lab41/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.agcinstruments.lab41/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
This is the strings.xml file i use to populate the array.
<resources>
<string name="app_name">lab4.1</string>
<string name="calculate">CALCULATE</string>
<string-array name="color_array1">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
<string-array name="color_array2">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
<string-array name="color_array3">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
<string-array name="color_array4">
<item>BLACK</item>
<item>BROWN</item>
<item>RED</item>
<item>ORANGE</item>
<item>YELLOW</item>
<item>GREEN</item>
<item>BLUE</item>
<item>PURPLE</item>
<item>GREY</item>
<item>WHITE</item>
</string-array>
I am do not know a lot of JAVA this is a stumbling block on my road to enlightnment hopefully. Any help would be greatly appreciated. I have spent hours trying to figure out a solution.

Missing button while executing first official Android tutorial

I am following official Android tutorial, but when I start the application, I obtain
instead of getting
Hereunder main files of the sample project
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AndroidTest</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
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.androidtest.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/edit_message" />
</RelativeLayout>
MainActivity.java
package com.example.androidtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
System details:
Fedora 20;
Android 4.4.4;
Eclipse 4.4;
ADB
I think you never attach the fragment into the activity.
Try to copy the fragment_main.xml into activity_main.xml!
The problem is that you have to add the fragment to the main activity.
There you can see how:
http://developer.android.com/training/basics/fragments/creating.html
You must add to your main activity layout, in the place where you want to place fragment.
<fragment android:name="com.example.android.MainFragment"
android:id="#+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
Then you had to create the class of the fragment, and inflate the main activity with the main layout

Is it possible to store multiple string values in internal storage?

Is it possible to store multiple string values in internal storage.If it's possible means please provide an general syntax to store multiple string values in internal storage.
as an example
make a layout as follows
<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=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="182dp"
android:onClick="save"
android:text="#string/save" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="46dp"
android:onClick="read"
android:text="#string/read" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="23dp"
android:ems="10"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
and write a code for android activity as follows
package com.example.storage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et;
private String data;
private String file = "mydata";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText)(findViewById(R.id.editText1));
}
public void save(View view){
data = et.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file saved",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void read(View view){
try{
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
et.setText(temp);
Toast.makeText(getBaseContext(),"file read",
Toast.LENGTH_SHORT).show();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Storage</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="save">save to intenal storage</string>
<string name="read">load from intenal storag</string>
</resources>
for yours purpose what you can do is, you can use a delimiter like a pipe sign as '|' between two strings while inserting the string values and than after reading the file you can separate string values an the basis of the delimiter '|'.
for more read http://www.tutorialspoint.com/android/android_internal_storage.htm

edit_message can not be resolved or is not a field

I am getting this error. It says "edit_message can not be ressolved or is not a field" Can somebody tell me why I am getting this error is how can I fix it.
LAYOUT OF MAIN ACTIVITY: -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
</LinearLayout>
CODE OF MAIN ACTIVITY
package com.practice.firstapp1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE= "com.practice.fristapp1.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Called when the user clicks the Send button */
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message); ///********ERRORR***********
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
LAYOUT OF SECOND ACTIVITY: -
<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=".DisplayMessageActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
CODE OF SECOND ACTIVITY: -
package com.practice.firstapp1;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
STRING RESOURCES:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="title_activity_display_message">My Message</string>
<string name="hello_world">Hello world!</string>
</resources>
It looks like your code is right. Check the following things:
1) Save the layouts in xml, one reason could be its not saved.
2) Check there is no error in your xmls and project is build.
3) If you are using eclipse, go to Projects->Clean All Projects and then projects->Build Automatically.
4) Open your activity and press "cmd + shift + o" or ctrl+ shift+o (in windows). It shall import the R.java, select the com..R in the options.
I hope it shall solve the error.
You're missing import com.practice.firstapp1.R in MainActivity.java.
See the docs on Accessing Resources for more information.

Categories

Resources