MenuInflater not working R cannot be resoved to a variable - java

I've looked at a bunch of posts on this subject, but nothing seems to be working and I've been stuck on this problem for 2 days now. these lines of code are getting red underline on the "R" saying it cannot be resolved as a variable
symbols = (EditText) findViewById(R.id.editText1);
results = (TextView) findViewById(R.id.textView2);
Button button = (Button) findViewById(R.id.button1);
Also this line of code at the bottom of the java file has the same error
getMenuInflater().inflate(R.menu.activity_main, menu);
I created a menu folder under res and a menu.xml file as well.
Here's all the code and a screenshot of my environment. I'm not sure which file you need to see so I provided them all just in case.
Screenshot of Environment
http://postimg.org/image/6d1l0909r/
MainActivity.Java
package com.example.stocks;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.net.MalformedURLException;
import android.os.Handler;
public class MainActivity extends Activity implements Runnable {
String symbolsStr = "";
String resultsStr = "";
EditText symbols = null;
TextView results = null;
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
results.setText(resultsStr);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
symbols = (EditText) findViewById(R.id.editText1);
results = (TextView) findViewById(R.id.textView2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
symbolsStr = symbols.getText().toString();
Thread thread = new Thread(MainActivity.this);
thread.start();
}
});
}
#Override
public void run() {
try {
resultsStr = GetQuotes(symbolsStr);
mHandler.post(mUpdateResults);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String GetQuotes(String symbols) throws MalformedURLException,
IOException {
StringBuilder response = new StringBuilder();
// call web service to get results
String urlStr = "http://download.finance.yahoo.com/d/quotes.csv?s="
+ symbols + "&f=nsl1op";
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
response.append("\n");
}
input.close();
}
return response.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.activity_main, menu);
return true;
}
}
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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="44dp"
android:text="Enter Symbols separated by commas:" />
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="16dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="44dp"
android:text="Look Up" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:layout_marginTop="33dp"
android:text="Results" />
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">StockQuotes</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
menu.xml
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/item1"></item>
<item android:id="#+id/item2"></item>
<item android:id="#+id/item3"></item>
</menu>
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stockquotes"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.stockquotes.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Your packages mismatch:
In Activity: package com.example.stocks;
In Manifest:
package="com.example.stockquotes"
Use 1 of them and rebuild your project.

Related

How to paste data from previous activity?

I'm trying here to make a project, that can scan a barcode (that is done), and after that it's supposed to show some values from a database based on that barcode (product name, address).
I manage to copy the value from the barcode to the clipboard, but then I cannot manage to copy it to the activity_second.xml's EditText.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.exemplozxingintegration"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="ScannerBucatarie"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="ScannerBucatarie"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.zxing.client.android.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:label="ZXing ScanBar"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden">
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/title_activity_second"></activity>
</application>
</manifest>
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 09.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/test/getData.php?id=";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_VC = "vc";
public static final String JSON_ARRAY = "result";
}
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}` AndroidManifet.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.exemplozxingintegration"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 09.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/test/getData.php?id=";
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_VC = "vc";
public static final String JSON_ARRAY = "result";
}
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".SecondActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/txResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/buttonGet"
android:text="Get"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:onClick="callZXing"
android:id="#+id/Button" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<TextView
android:id="#+id/txResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rezultat:"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Is this the correct code?"
android:id="#+id/textView"
android:layout_marginTop="70dp"
android:layout_gravity="center_horizontal" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="Yes"
android:layout_marginTop="30dp"
android:id="#+id/button2"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="sendSecond" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="No"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="callZXing" />
</LinearLayout>
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}
In your main activity, set your data into Intent as below:
Intent intent = getIntent();
intent.putExtra("Param_name", txtNumOfCards.getText().toString());
intent.setClass(this, SecondActivity.class);
startActivity(intent);
In the second activity, you can retrieve it as below:
Intent intent = getIntent();
String value = intent.getStringExtra("Param_name");
Checkout the following exmaple:
http://www.startandroid.ru/en/lessons/complete-list/241-lesson-28-extras-passing-data-using-intent.html
As #Mohammed Kharma explained, you must send the id as an Intent extra (no need to copy it to the clipboard). I believe you already created this Intent, but I'm recreating it. Have in mind that I don't know the name you chose for your intent, so I'll just call it 'i'.
On your MainActivity.java:
Intent i= new Intent(MainActivity.class,SecondActivity.java);
i.putExtra("barcode",txtResult.getText().toString());
startActivity(i);
On your SecondActivity.java:
textViewResult = (TextView) findViewById(R.id.textViewResult);
String barcode=getIntent().getStringExtra("barcode");
textViewResult.setText(barcode);

Set image in app as wallpaper

I am not able to set an image from the app as wallpaper. On running it shows unfortunately testandroid stopped working.
I have set the permission in the manifest file and set minimum SDK to 5.
Androidmanifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="19" />
<uses-permission android:maxSdkVersion="19" android:name="android.permission.SET_WALLPAPER"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testandroid.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
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.testandroid.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<ImageView
android:id="#+id/imageview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/bing"
android:adjustViewBounds="true"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="14dp"
android:layout_marginTop="27dp"
android:text="#string/btn"
android:onClick="goForNext"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn1"
android:onClick="setWallpaper"/>
</LinearLayout>
MainActivity.java
package com.example.testandroid;
import android.app.WallpaperManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imgview = (ImageView) findViewById(R.id.imageview1);
imgview.setImageResource(R.drawable.bing);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void goForNext(View view){
Button but = (Button) findViewById(R.id.button1);
Intent i = new Intent(MainActivity.this, Activity.class);
startActivity(i);
}
public void setWallpaper(View view)
{
Button bt = (Button) findViewById(R.id.button2);
WallpaperManager wm = WallpaperManager.getInstance(getApplicationContext());
try
{
wm.setResource(R.drawable.bing);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is the activity_main.xml file. please help me wiht it.
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.testandroid.MainActivity"
tools:ignore="MergeRootFrame" />
Try removing the following from onCreate()
ImageView imgview = (ImageView) findViewById(R.id.imageview1);
imgview.setImageResource(R.drawable.bing);
And add this to your onCreateView() method in your Fragment
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
ImageView imgview = (ImageView) rootView.findViewById(R.id.imageview1);
imgview.setImageResource(R.drawable.bing);
return rootView;

Intent isn't working, on clicking on the button2, application crashes

I am not able to switch between activities, when I click on the button2, the application crashes down.
MainActivity.Java
<pre>package com.example.againtry;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Declare our View Variables and assign them the Views from the layout file
final TextView answerLabel = (TextView) findViewById(R.id.textView1);
Button getAnswerButton = (Button) findViewById(R.id.button1);
getAnswerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// The Button was clicked, so the update the answer label with an answer
String answer = "";
// Randomly select one of three answers: Yes, No or May be
// Update the label with our dynamic answer
Random randomGenerator = new Random(); // Construct a new Random number Generator
int randomNumber = randomGenerator.nextInt(3);
answer = Integer.toString(randomNumber);
// update the label with our dynamic answer
answerLabel.setText(answer);
}});
Button btnSimple= (Button) findViewById(R.id.button2);
btnSimple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// From One Activity to another
Intent intent = new Intent(MainActivity.this, SendMessageActivity.class);
startActivity(intent);
}});
}
#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;
}}</pre>
This is my Second Activity
SendMessageActivity.Java
<pre>package com.example.againtry;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SendMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_message);
final EditText editSMS = (EditText) findViewById(R.id.editText1);
final EditText editPhoneNum = (EditText) findViewById(R.id.phoneNum);
Button getSendButton = (Button) findViewById(R.id.button1);
getSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNo = editPhoneNum.getText().toString();
String sms = editSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.send_message, menu);
return true;
}
}</pre>
Manifest
<pre> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.againtry"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<uses-permission android:maxSdkVersion="10" android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:maxSdkVersion="10" android:name="android.permission.SEND_SMS"/>
<uses-permission android:maxSdkVersion="10" android:name="android.permission.READ_SMS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.againtry.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.againtry.SendMessageActivity"
android:label="#string/title_activity_send_message" >
</activity>
</application>
</manifest></pre>
activity_main<pre>
<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:gravity="bottom"
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"
style="#android:style/ButtonBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:text="Enlighten Me!" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="177dp"
android:textSize="32sp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignLeft="#+id/button1"
android:layout_marginBottom="44dp"
android:text="Message" />
</RelativeLayout></pre>
send_message.xml<pre>
<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=".SendMessageActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:ems="10"
android:hint="Enter your message" >
<requestFocus />
</EditText>
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="#string/button_send" />
<TextView
android:id="#+id/messageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_alignParentTop="true"
android:layout_marginTop="77dp"
android:text="TextView" />
<EditText
android:id="#+id/phoneNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/messageView1"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="Enter Phone Number" android:inputType="number"/>
</RelativeLayout></pre>
In the layout of SendMessageActivity (i.e send_message.xml), you have no buttons with id "button1".
So when doing :
Button getSendButton = (Button) findViewById(R.id.button1);
findViewById returns null and hence getSendButton.setOnClickListener(/***/); throws a NullPointerException.
It should be :
Button getSendButton = (Button) findViewById(R.id.sendButton);
You have to assign onclick to a particular button which i don't see in your activity_main xml.
just add onclick event to your button and remove onclicklistener and it should work.
to add onclick listener you can go to designer page and in properties you will find a tag as onclick.Just assign the onlick method to that tag using dropdown.
there is mistake in mapping of control in SendMessageActivity
public class SendMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_message);
final EditText editSMS = (EditText) findViewById(R.id.editText1);
final EditText editPhoneNum = (EditText) findViewById(R.id.phoneNum);
Button getSendButton = (Button) findViewById(R.id.button1);
instead of button1 it should be R.id.sendButton

Using SOAP web services.. app doesn't work properly

I am following this tutorial to use SOAP web services.
At first it presented some problems but after doing a few things (mentioned in the comments on the tutorial), it started working, but it is not working properly.
The problem is that after adding the input in the edit text, when i click on the corresponding number to convert the temperature, it does not do anything.
I am pasting the code below, This is an external link for LogCat (of pastebin.com, where I am pasting the logcat) since adding it here exceeds the permissible length of the question
.
Any hint/help will be greatly appreciated. Thank you in advance.
LAYOUT:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textView1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/txtFar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/editText1">
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textView2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/txtCel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/editText2"/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnFar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/btnFar" />
<Button
android:id="#+id/btnCel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="#string/btnCel" />
</LinearLayout>
<Button
android:id="#+id/btnClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btnClear" />
</LinearLayout>
CODE:-
package com.webservice;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "FahrenheitToCelsius";
private static String METHOD_NAME2 = "CelsiusToFahrenheit";
private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_service_demo);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtCel.setText(result.getProperty(0).toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnCel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);
//Use this to add parameters
request.addProperty("Celsius",txtCel.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION2, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtFar.setText(result.getProperty(0).toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
}
STRINGS RESOURCE:-
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Using SOAP Test 2</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name= "textView1">Fahrenheit</string>
<string name="editText1">0</string>
<string name= "textView2">Celsius</string>
<string name="editText2">0</string>
<string name="btnFar">Convert to Celsius</string>
<string name="btnCel">Convert to Fahrenheit</string>
<string name="btnClear">Clear</string>
</resources>
MANIFEST FILE:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.webservice.WebServiceDemoActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is the exception you are getting:
java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
To resolve this problem, you need to copy the ksoap2-android-assembly-2.6.2-jar-with-dependencies.jar to the /libs folder of your project then rebuild the project. Then Eclipse ADT will automatically add this jar to the buildpath of your project.
I have followed the same tutorial.
This worked for me: i have changed
private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE = "http://tempuri.org/";
with
private static String SOAP_ACTION1 = "http://www.w3schools.com/webservices/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
private static String NAMESPACE = "http://www.w3schools.com/webservices/";
For finding the correct name space, you have to browse the web service URL. In this case: http://www.w3schools.com/webservices/tempconvert.asmx?WSDL. Then, you can find the correct name space at targetNamespace="........"

Android Tutorial issue

I am new to android, Eclipse and Java.
I started these tutorials from here: http://developer.android.com/training/basics/firstapp/index.html
I did all the steps from the link above...my problem is when I run this app and press the 'Send' button...nothing happens, there are no errors in my Console or LogCat.
Here is my code I ended up with:
activity_main.xml:
<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"
android:onClick="sendMessage" />
</LinearLayout>
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyFirstApp</string>
<string name="action_settings">Settings</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</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>
MainActivity.java:
package com.example.myfirstapp;
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.example.myfirstapp.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;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
}
}
DisplayMessageActivity.java:
package com.example.myfirstapp;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and activity_display_message.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=".DisplayMessageActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Has anyone else ran into the same issue as me? Any help would be appreciated.
MyFirstApp Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
</manifest>
You need to call startActivity
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent); // missing
}
Also make sure you have made an entry for the activities in manifest file.

Categories