With my Android project created with latest version of Eclipse+ADT I cannot access parse.com api. If I use the prepackaged project from parse.com I can access. But If I create a new Android project from scratch I cannot. I suspect the problem is because of parse initialization and fragments. As prepackaged project from parse.com doesn't use fragments. In this program first button should add an object to database but that doesnt work.. Can anyone know solution for this?
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.deneme.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_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.deneme.MainActivity$PlaceholderFragment" >
<LinearLayout
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip"
android:layout_below="#+id/txtTitle">
<Button
android:id="#+id/btnCreate"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:layout_weight="1.0"
android:text="Add Object"
android:textColor="#android:color/white"
android:textSize="25sp" />
<Button
android:id="#+id/btnIncrement"
android:layout_width="fill_parent"
android:layout_height="0.0dip"
android:layout_weight="1.0"
android:text="Increment votes"
android:textColor="#android:color/white"
android:textSize="25sp" />
</LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deneme"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="denemeApp"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.deneme.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>
denemeApp.java
package com.example.deneme;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseUser;
import android.app.Application;
public class denemeApp extends Application {
#Override
public void onCreate() {
super.onCreate();
// Add your initialization code here
Parse.initialize(this, "KEY1", "KEY2");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
MainActivity.java:
package com.example.deneme;
import com.example.deneme.R;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
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.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
Button btnCreate = (Button)rootView.findViewById(R.id.btnCreate);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject testObject = new ParseObject("testobject");
testObject.put("total_votes", 0);
testObject.saveInBackground();
}
});
Button btnIncrement = (Button)rootView.findViewById(R.id.btnIncrement);
btnIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//works with "testobject" and "7erUqKQn1P"
//doesnt work "testobject2" and "1g68ZP1ikc"
ParseQuery<ParseObject> query = ParseQuery.getQuery("testobject");
query.getInBackground("7erUqKQn1P", new GetCallback<ParseObject>()
{
public void done(ParseObject vote, ParseException e)
{
if(e == null)
{
vote.increment("total_votes");
vote.saveInBackground();
}
}//done
}//new GetCallback
);//query.getInBackground
}
});
return rootView;
}
}
}
You need to add this permission to your AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
Related
I am trying to develop an application whereby there would be one activity with a start button. Upon pressing the start button, it would lead me to a new activity where the timer starts to run. I am only able to make it run when both buttons and textview is on the same page. However, I would like to have button on one activity and textview on another activity.
Java File:
import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
Button buttonStart;
TextView textCounter;
MyCountDownTimer myCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button)findViewById(R.id.start);
textCounter = (TextView)findViewById(R.id.counter);
buttonStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myCountDownTimer = new MyCountDownTimer(30000, 1000, textCounter);
myCountDownTimer.start();
}
});
}
public class MyCountDownTimer extends CountDownTimer {
private TextView textCounter;
public MyCountDownTimer(long millisInFuture, long countDownInterval, TextView textCounter) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
#Override
public void onTick(long millisUntilFinished){
this.textCounter.setText(millisUntilFinished / 1000l + " seconds remaining ");
}
#Override
public void onFinish() {
this.textCounter.setText("Finished");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Main_Activity:
<Button
android:id="#+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/Button"
android:clickable="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
Main_Activity2:
<TextView
android:id="#+id/counter"
android:layout_width="300dp"
android:layout_height="300dp"
android:textStyle="bold"
android:textSize="50sp"
android:gravity="center"
android:layout_marginTop="50dp"
android:clickable="false"
android:enabled="false" />
Try this Code:
The code for Layout 1: activity_main.xml , Only with start button
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="true"
android:text="Start" />
</LinearLayout>
The code for Layout 2: count_down_activity.xml
<?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/counter"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:gravity="center"
android:textSize="50sp"
android:textStyle="bold" />
</LinearLayout>
Java file: MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
Button startBrowser = (Button) findViewById(R.id.start);
startBrowser.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(mContext, CountDownActivity.class));
}
});
}
#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;
}
}
Java File 2: CountDownActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.widget.TextView;
public class CountDownActivity extends Activity {
TextView textCounter;
MyCountDownTimer myCountDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.count_down_activity);
textCounter = (TextView)findViewById(R.id.counter);
myCountDownTimer = new MyCountDownTimer(30000, 1000, textCounter);
myCountDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
private TextView textCounter;
public MyCountDownTimer(long millisInFuture, long countDownInterval, TextView textCounter) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
#Override
public void onTick(long millisUntilFinished) {
this.textCounter.setText(millisUntilFinished / 1000l + " seconds remaining : ");
}
#Override
public void onFinish() {
this.textCounter.setText("Finished");
}
}
#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;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidsample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidsample.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.androidsample.CountDownActivity"
android:screenOrientation="portrait" >
</activity>
</application>
</manifest>
I already have a working Map fragment in my Activity.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_alignParentTop="true">
<android.support.design.widget.FloatingActionButton
android:id="#+id/add"
android:onClick="locate_me"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginTop="360dp"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:clickable="true"
android:src="#drawable/tick"
app:backgroundTint="#000"
android:layout_gravity="right|end"
app:layout_anchorGravity="right|end"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:onClick="locate_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:clickable="true"
android:src="#drawable/mylocation"
app:backgroundTint="#000000"
android:layout_gravity="bottom|end"
app:layout_anchorGravity="right|end"/>
</fragment></android.support.v4.widget.DrawerLayout>
I want to add a Drawer Layout to this existing Activity. I have tried a lot but couldn't make it work. I have tried MapView as well. Can you give me some pointers? Thanks.
So this is pretty straight forward Here is a gist, with all the code below.
Dependency section of my build.gradle :
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.google.android.gms:play-services:7.8.0'
compile 'com.android.support:design:23.0.0'
}
XML file for my AppCompatActivity which includes the drawer layout and a SupportMapFragment, since I am using appcompat-v7 for this project:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="16dp"
android:clickable="true"
android:src="#drawable/ic_maps_navigation"
app:backgroundTint="#777"
android:layout_gravity="bottom|end"/>
</FrameLayout>
<FrameLayout
android:id="#+id/nav_container"
android:layout_gravity="start"
android:layout_width="240dp"
android:layout_height="fill_parent"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
Then I have a single activity:
package com.test.mapdrawer;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements DrawerFragment.NavCallback {
private DrawerLayout drawer;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout) findViewById(R.id.drawer);
setupDrawerLayout();
if(savedInstanceState == null) {
/*
Load the fragment for the drawer
*/
getSupportFragmentManager()
.beginTransaction()
.add(R.id.nav_container, DrawerFragment.newInstance(), "Drawer")
.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
// Handle the drawer Actions
if(mDrawerToggle.onOptionsItemSelected(item)){
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerLayout(){
// Instantiate the Drawer Toggle
mDrawerToggle = new ActionBarDrawerToggle(this, drawer, R.string.app_name, R.string.app_name){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
getSupportActionBar().setTitle(getString(R.string.app_name));
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
getSupportActionBar().setTitle(getString(R.string.app_name));
}
};
// Set the Toggle on the Drawer, And tell the Action Bar Up Icon to show
drawer.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onNavSelected(int position) {
Toast.makeText(this, "Selected item: "+ position + " from nav", Toast.LENGTH_SHORT).show();
}
}
And finally your typical Manifest for a Map project:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.mapdrawer" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="<YOUR_MAPS_API_KEY_HERE>"/>
<activity
android:name=".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>
Then you want to create and populate the Navigation Drawer Fragment:
package com.test.mapdrawer;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DrawerFragment extends Fragment {
private static final String [] NAV_ITEMS = {"Home", "Nav Item 2", " Nav Item 3", "Nav Item 4"};
private ListView mListView;
private NavCallback mCallback;
public interface NavCallback{
void onNavSelected(int position);
}
/**
* Create a static method to return this fragment
* #return - this fragment
*/
public static DrawerFragment newInstance(){
return new DrawerFragment();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (MainActivity) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.drawer_fragment, container, false);
/*
You can really use anything you want here but for simplicity lest assume ListView
*/
mListView = (ListView) view.findViewById(R.id.listViewNav);
mListView.setOnItemClickListener(ListListener);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Simple adapter, Also this is for simplicity and adapter can be used
mListView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, NAV_ITEMS));
}
private final AdapterView.OnItemClickListener ListListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCallback.onNavSelected(position);
}
};
}
Which has layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#android:color/black">
<ListView
android:id="#+id/listViewNav"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Please note I have updated 2 files for this Change and added 2
MainActivity -> now implements interface and onCreate contains logic to load fragment
activity_main.xml -> FrameLayout background for drawer is removed
New Drawerfragment
New drawer_fragment.xml
Also, the gist has been update to reflect these changes, happy coding!
I am trying to add fragment in my main activity which I'd created as blank activity. I actually want to launch zxing module by button click from my app.
I removed 3 lines of code from oncreate method and inserted it in onClick method of PlaceholderFragment class.
but fragment is not working properly.
I could not understand in Which xml file What code to add?
here is my code:
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: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=".MainActivity"
android:background="#bcff9420">
<TextView android:text="#string/WelcomeStr" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtWelcome"
style="#style/Base.TextAppearance.AppCompat.Title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/scanStr"
android:id="#+id/btnScan"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="examples.skan.zxing_demo" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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.google.zxing.client.android.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="landscape"
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>
</application>
</manifest>
MainActivity.java
package examples.skan.zxing_demo;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
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;
public class MainActivity extends ActionBarActivity {
#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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
public static class PlaceholderFragment extends Fragment implements View.OnClickListener{
View rootView;
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.fragment_main,container,false);
return rootView;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnScan:
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
break;
}
}
}
}
activity blank XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity Java.
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, new SettingsFragment(), "fragmentTag")
.disallowAddToBackStack()
.commit();
}
}
Android TextView is failing with null pointer exception
and its failing at "disp.setText("0");"
inside the method "protected void onCreate(Bundle savedInstanceState) {"
I tried most of the suggestions provided in net. Still could not resolve it.
Please need help....
My Layout: "fragment_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:onClick="num_Clicked"
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.ullas.Test1.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:gravity="right"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
and My Activity is : "MainActivity.java"
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
TextView disp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
disp = (TextView)findViewById(R.id.textView1);
disp.setText("0");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
you tell your layout is "fragment_main.xml" and textview is in this xml.
in your code, you are setting a different layout xml:
setContentView(R.layout.activity_main);
disp = (TextView)findViewById(R.id.textView1);
you must set the layout you want to use, in order to be able to reach your textview:
setContentView(R.layout.fragment_main);
disp = (TextView)findViewById(R.id.textView1);
The view textView1 is not found in the layout file loaded. View hierarchy should be created before getting view from the layout.
Complete "MainActivity.java" is below
package com.example.test;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView disp;
disp = (TextView) findViewById(R.id.textView1);
disp.setText("0");
if (savedInstanceState == null) {
getFragmentManager().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;
}
}
}
and Below is the Complete "fragment_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.test.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:gravity="right"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Below is the "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.test.MainActivity"
tools:ignore="MergeRootFrame" />
and ONE MORE THING , WHEN I CREATE A NEW PROJECT BY DEFAULT IT WILL GIVE ME THIS "Fragment_main.xml"
I've gone through the MyFirstApp tutorial to the point where the app should run and when you press the send button a new screen should appear , but instead of a new screen appearing it crashes with the 'Unfortunately, MyFirstApp has stopped' message.
I'm new to app development so I need basic instructions.
Manifest.xml
<?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>
main activity 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.MESSAAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view) {
//do something
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);
}
#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;
}
}'
DisplayMessageActivty
package com.example.myfirstapp;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public 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);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_display_message
package com.example.myfirstapp;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
public 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);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}'
Activity_main
<?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_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
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"?>
<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_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
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>'
Thanks
Your callback for the Button called sendMessage while you declared sendmessage in xml.