I try to realise following view in androind application.
In my programm i want to divide the main activity between two.
Now it does't work propertly. I want, that the line between two
windows in activity is moveable and the line can divide the whole screen in
different proportion. Not only to show whole one window or another.
Image for understanding enter link description here
My programm looks like:
MainActivity.java
package dva.checkin;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity implements
OnMyLocationChangeListener {
private boolean firstStart = true;
private GoogleMap map;
private LinearLayout listView;
private LinearLayout mapView;
private View divider;
private float touchActionDownX;
private float touchActionDownY;
private ListView dataList;
private void initCustomList() {
dataList = (ListView) findViewById(R.id.locations_list);
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initCustomList();
listView = (LinearLayout) findViewById(R.id.list_view);
mapView = (LinearLayout) findViewById(R.id.map_view);
divider = (View) findViewById(R.id.divider);
divider.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
divider.setBackgroundColor(Color.parseColor("#FF0000"));
touchActionDownX = event.getRawX();
touchActionDownY = event.getRawY();
Log.i("DOWN", "" + touchActionDownX + " ; "
+ touchActionDownY);
break;
case MotionEvent.ACTION_MOVE: {
// Log.i("test","Move");
float touchActionMoveX = event.getRawX();
float touchActionMoveY = event.getRawY();
Log.i("MOVE", "down " + touchActionDownX + " ; "
+ touchActionDownY);
Log.i("MOVE", "curr " + touchActionMoveX + " ; "
+ touchActionMoveY);
if (touchActionMoveX < touchActionDownX) {
Log.i("MOVE UP", ""
+ (touchActionMoveX - touchActionDownX));
// UP
LinearLayout.LayoutParams lpar = (LinearLayout.LayoutParams) listView
.getLayoutParams();
LinearLayout.LayoutParams mpar = (LinearLayout.LayoutParams) mapView
.getLayoutParams();
if (lpar.weight > 0.2) {
lpar.weight -= 0.1;
mpar.weight += 0.1;
}
listView.setLayoutParams(lpar);
mapView.setLayoutParams(mpar);
} else if (touchActionMoveX >= touchActionDownX) {
// DOWN
Log.i("MOVE DOWN", ""
+ (touchActionDownX - touchActionMoveX));
LinearLayout.LayoutParams lpar = (LinearLayout.LayoutParams) listView
.getLayoutParams();
LinearLayout.LayoutParams mpar = (LinearLayout.LayoutParams) mapView
.getLayoutParams();
if (mpar.weight > 0.2) {
mpar.weight -= 0.1;
lpar.weight += 0.1;
}
listView.setLayoutParams(lpar);
mapView.setLayoutParams(mpar);
}
touchActionDownX = touchActionMoveX;
touchActionDownY = touchActionMoveY;
break;
}
case MotionEvent.ACTION_UP:
divider.setBackgroundColor(Color.parseColor("#00FF00"));
break;
}
return true;
}
});
}
#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 void onMyLocationChange(Location location) {
if (firstStart) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location
.getLongitude())).zoom(18).build();
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
firstStart = false;
}
}
}
than activity_main.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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical"
android:id="#+id/list_view" >
<Button
android:id="#+id/checkin"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/checkin"
android:onClick="checkIn"/>
<ListView
android:id="#+id/locations_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp" >
</ListView>
</LinearLayout>
<View android:id="#+id/divider"
android:layout_height="15dip"
android:background="#00ff00"
android:layout_width="fill_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical"
android:id="#+id/map_view">
</LinearLayout>
</LinearLayout>
and AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dva.checkin"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<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="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="dva.checkin.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="dva.checkin.CheckinDetailsActivity"
android:parentActivityName="dva.checkin.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="dva.checkin.MainActivity" />
</activity>
<activity android:name=".DisplayImageActivity"></activity>
</application>
</manifest>
Thanks for suggestions!
Related
I wish to implement a webview in the fragment_home_screen without covering the BottomNavigationView. However, even I followed everything on an online tutorial by setting up the webview in the Fragment_Home.java onCreateView() method. Nothing has showed up. I tried adding a button in the fragment_home_screen.xml to ensure the fragment DID showed up. It ended up showing the BUTTON ONLY.
I have been trying to fix this issues for hours and still couldn't figuring what's wrong with my code. Got any idea?
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.exercise.myApplication">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".Activity_Map"
android:exported="false"
android:label="#string/title_activity_map" />
<activity
android:name=".Activity_Login"
android:exported="false" />
<activity
android:name=".Activity_SignUp"
android:exported="false" />
<activity
android:name=".Activity_Home"
android:exported="false"
android:label="Main" />
<activity
android:name=".SplashScreen"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Activity_Home.java
package android.exercise.myApplication;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class Activity_Home extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
BottomNavigationView bottomNav = findViewById(R.id.bottomNavigationView);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectFragment = null;
switch(item.getItemId()){
case R.id.homeScreen:
selectFragment = new HomeFragment();
break;
case R.id.userScreen:
selectFragment = new Fragment_User();
break;
case R.id.driverScreen:
selectFragment = new Fragment_Driver();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectFragment).commit();
return true;
}
};
}
Fragment_Home.java
package android.exercise.myApplication;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Fragment_Home#newInstance} factory method to
* create an instance of this fragment.
*/
public class Fragment_Home extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Fragment_Home() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Fragment_Home.
*/
// TODO: Rename and change types and number of parameters
public static Fragment_Home newInstance(String param1, String param2) {
Fragment_Home fragment = new Fragment_Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String url = "https://pastebin.com/";
View v = inflater.inflate(R.layout.fragment_home_screen, container, false);
WebView myWebview = (WebView) v.findViewById(R.id.webview);
myWebview.getSettings().setJavaScriptEnabled(true);
myWebview.getSettings().setDomStorageEnabled(true);
myWebview.setWebViewClient(new WebViewClient());
myWebview.loadUrl("https://en.wikipedia.org/");
myWebview.setWebViewClient(
new SSLWebViewClient()
);
myWebview.clearView();
myWebview.measure(100, 100);
myWebview.getSettings().setUseWideViewPort(true);
myWebview.getSettings().setLoadWithOverviewMode(true);
return v;
}
}
activity_main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".Activity_Home" >
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu"/>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/fragment_container"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_home_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".Fragment_Home">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</WebView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintStart_toStartOf="#+id/webview"
app:layout_constraintTop_toTopOf="#+id/webview" />
</RelativeLayout>
As for the logcat, filtered with warnings there's only one line of error:
022-01-19 21:45:53.557 7053-7053/android.exercise.myApplication E/chromium: [ERROR:gl_surface_egl.cc(549)] eglChooseConfig failed with error EGL_SUCCESS
I tried your code and it works fine you just need to comment out some code in Fragment_Home.java as below:
#Override
public View onCreateView(....){
.....
..........
//remove or comment this part.
// myWebView.setWebViewClient(new SSLWebViewClient());
.....
}
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.
I have a Android App. I need to integrate admob. I have included the following code but banner ad is not displaying in main layout please help regarding this your answers will be appreciated and it would be a great help. thank you.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:background="#drawable/hanumanji1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HanumanActivity" >
<Button
android:id="#+id/pause_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/circle_shape_drawable"
android:text="#string/pau"
android:textColor="#ffff00" />
<Button
android:id="#+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/circle_shape_drawable"
android:gravity="center"
android:text="#string/pl"
android:textColor="#ffff00" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/circle_shape_drawable"
android:gravity="center"
android:text="#string/de"
android:textColor="#ffff00" />
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ads:loadAdOnCreate="true"/>
</RelativeLayout>
MainActivity.java
package e.hanuman;
import e.hanuman.Constants;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import e.hanuman.R;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class HanumanActivity extends Activity implements OnClickListener{
Button play_button, pause_button, button1 ;
private AdView adView;
MediaPlayer player;
private int[] LEAVES = {
R.drawable.leaf_green,
R.drawable.leaf_red,
R.drawable.leaf_yellow,
R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hanuman);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="#+id/mainLayout"
RelativeLayout layout = (RelativeLayout)findViewById(R.id.main_layout);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest();
//adRequest.setTesting(true);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
getInit();
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, 5000);
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
player.pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
player.start();
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
player.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(HanumanActivity.this);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
animationLayout.width = (int) (60*mScale);
animationLayout.height = (int) (60*mScale);
startAnimation(imageView);
}
};
private class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
public void getInit() {
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
player = MediaPlayer.create(this, R.raw.hanu);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
player.start();
break;
case R.id.pause_button:
player.pause();
break;
case R.id.button1:
button1Click();
break;
}}
private void button1Click() {
// TODO Auto-generated method stub
startActivity(new Intent("e.hanuman.details"));
}
#Override
public void onBackPressed(){
if(player != null && player.isPlaying())
player.stop();
finish();
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
MANIFEST XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="e.hanuman"
android:versionCode="4"
android:versionName="4.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/hanuman"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:name="e.hanuman.Splash" 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="e.hanuman.HanumanActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="details"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="e.hanuman.details" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
Change com.google.android.ads to com.google.android.gms.ads In your main activity and your manifest because you're using the old ads, use the .gms change your xml too, to the .gms adview.
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;
I'm trying to write a basic drawing Android app for android and test it on Genymotion, but I can't click on the app icon (it says "Unfortunately [app] has stopped.")
I'm not sure if the three private variables should be under the MainActivity class? Or that it has to do with my AndroidManifest.xml file. Can someone look over my code?
My MainActivity.java file:
package edu.berkeley.cs160.opalkale.prog2;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Paint;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private Paint myPaint;
private ImageButton currPaint;
private myView drawView;
public void paintClicked(View view) {
if (view != currPaint) {
// update color
ImageButton imgView = (ImageButton) view;
String color = view.getTag().toString();
drawView.setColor(color);
imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
currPaint = (ImageButton)view;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView mV = new myView(this, null);
setContentView(mV);
drawView = (myView) findViewById(R.id.drawing);
LinearLayout paintLayout = (LinearLayout) findViewById(R.id.paint_colors);
currPaint = (ImageButton) paintLayout.getChildAt(0);
currPaint.setImageDrawable(getResources().getDrawable(
R.drawable.paint_pressed));
}
#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;
}
}
My AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.berkeley.cs160.opalkale.prog2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="edu.berkeley.cs160.opalkale.prog2.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>
Logcat:
[2014-02-11 23:04:43 - DeviceMonitor] Adb connection Error:EOF
[2014-02-11 23:04:43 - DeviceMonitor] Sending jdwp tracking request failed!
[2014-02-11 23:04:43 - DeviceMonitor] Connection attempts: 1
[2014-02-11 23:04:44 - DeviceMonitor] Connection attempts: 2
[2014-02-11 23:04:45 - DeviceMonitor] Connection attempts: 3
[2014-02-11 23:04:46 - DeviceMonitor] Connection attempts: 4
[2014-02-11 23:04:47 - DeviceMonitor] Connection attempts: 5
[2014-02-11 23:04:48 - DeviceMonitor] Connection attempts: 6
[2014-02-11 23:04:49 - DeviceMonitor] Connection attempts: 7
[2014-02-11 23:04:50 - DeviceMonitor] Connection attempts: 8
[2014-02-11 23:04:51 - DeviceMonitor] Connection attempts: 9
[2014-02-11 23:04:52 - DeviceMonitor] Connection attempts: 10
[2014-02-11 23:04:53 - DeviceMonitor] Connection attempts: 11
[2014-02-11 23:07:14 - Logcat] device not found
com.android.ddmlib.AdbCommandRejectedException: device not found
at com.android.ddmlib.AdbHelper.setDevice(AdbHelper.java:774)
at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:396)
at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:347)
at com.android.ddmlib.Device.executeShellCommand(Device.java:444)
at com.android.ddmuilib.logcat.LogPanel$3.run(LogPanel.java:531)
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"
android:screenOrientation="portrait"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCCCCCC"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/new_btn"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:contentDescription="#string/brush"
android:src="#drawable/brush" />
</LinearLayout>
<edu.berkeley.cs160.opalkale.prog2.myView
android:id="#+id/drawing"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="3dp"
android:layout_weight="1"
android:background="#FFFFFFFF" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/paint_colors"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageButton
android:layout_width="#dimen/large_brush"
android:layout_height="#dimen/large_brush"
android:layout_margin="2dp"
android:background="#FF787878"
android:contentDescription="#string/paint"
android:onClick="paintClicked"
android:src="#drawable/paint"
android:tag="#FF787878" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
myView class:
package edu.berkeley.cs160.opalkale.prog2;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class myView extends View {
private Path drawPath;
private Paint drawPaint, canvasPaint;
private int paintColor = 0xFF787878;
private Canvas drawCanvas;
private Bitmap canvasBitmap;
public void setColor(String newColor){
//set color
invalidate();
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
}
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
private void setupDrawing() {
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(20);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// view given size
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
#Override
protected void onDraw(Canvas canvas) {
// draw view
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// detect user touch
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(touchX, touchY);
break;
case MotionEvent.ACTION_MOVE:
drawPath.lineTo(touchX, touchY);
break;
case MotionEvent.ACTION_UP:
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
}
setContentView(Id); is missing in your code.So it is giving you NullPointerException
Set some of the view to your Activity like
setContentView(R.layout.layout);
It is just a common problem with manifest your program "Unfortunately app has stopped" may be caused due to Manifest file, Because you have two classes:
So use this:
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="18" />
<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=".myView"
android:label="#string/app_name">
</activity>
</application>
NPE- Null Pointer Exception. No call to setContentView.
Also,
drawView = (myView) findViewById(R.id.drawing);
what is your myView ?
Please set myView as the view for your activity or call setContentView with the layout where R.id.drawing is.
Where is your layout.Your layout is missing. Use setContentView(R.layout.yourlayout);
Just remove comments from this line ,
// setContentView(mV);