Application stopped working when loading layout with setContentView - java

Here's the XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/search_lyt"
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"
android:name="search_act"
tools:context="com.example.app.Hisp$PlaceholderFragment">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/hispania_lgs"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/back2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Info"
android:id="#+id/info2"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/model_list"
android:layout_below="#+id/textViewML"
android:layout_alignParentRight="true"
android:layout_above="#+id/back2"
android:choiceMode="singleChoice" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select any of the models below and press Info for the model's specifications"
android:id="#+id/textViewML"
android:layout_below="#+id/imageView2"
android:layout_alignLeft="#+id/model_list" />
And using the setContentView method results in an 'Application stopped working'.
setContentView(R.layout.search_hisp);
Any idea on how to fix this? I'm quite new to Android Development and still trying to find how to switch layouts the correct way.
Well, even I change the onCreate()' setContentView to R.layout.search_hisp and gave me the error on startup. So my guess is it's probably from the XML file or something.
Thanks in advance!
Edit, there's the error:
>
03-25 12:10:23.415 20858-20858/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
at com.example.app.Hisp.beginSearch(Hisp.java:121)
at com.example.app.Hisp$3.onClick(Hisp.java:107)
at android.view.View.performClick(View.java:4231)
at android.view.View$PerformClick.run(View.java:17537)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Process: com.example.app
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Package: com.example.app v1 (1.0)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ Application Label: Hisp_Selector
And here's the code:
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.preference.DialogPreference;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.ViewGroup;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.widget.LinearLayout;
public class Hisp extends ActionBarActivity {
public static ActionBarActivity activity;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
activity = this;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_hisp);
TextView txt = (TextView) findViewById(R.id.textViewML);
Button btn = (Button) g(R.id.search);
Button rst = (Button) g(R.id.reset);
rst.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
finish();
startActivity(getIntent());
}
});
OnClickListener _rdb = new OnClickListener() {
#Override
public void onClick(View view) {
((CheckBox) g(R.id.R134a)).setChecked(false);
((CheckBox) g(R.id.R22)).setChecked(false);
((CheckBox) g(R.id.R404A)).setChecked(false);
((CheckBox) g(R.id.R507A)).setChecked(false);
((CheckBox) view).setChecked(true);
}
};
((CheckBox) g(R.id.R134a)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R22)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R404A)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R507A)).setOnClickListener(_rdb);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
beginSearch();
}
});
/*
if (stanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
*/
}
public void beginSearch() {
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Boolean err = false;
try {
if (!(Double.parseDouble((((EditText) g(R.id.capacity)).getText().toString().trim())) >= 0 &&
isBetween(-35, 5, Integer.parseInt(((EditText) g(R.id.evaptemp)).getText().toString().trim())) &&
isBetween(28, 58, Integer.parseInt(((EditText) g(R.id.condtemp)).getText().toString().trim())) &&
isBetween(5, 13, Integer.parseInt(((EditText) g(R.id.dt1)).getText().toString().trim()))
)) err = true;
} catch(Exception e) {
err = true;
}
if (err) {
showMessageBox("ERROR", "Make sure you have filled all the fields correctly.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
setContentView(R.layout.search_hisp);
}
}
public View g(int id) {
return activity.findViewById(id);
}
public Boolean isBetween(Integer i1, Integer i2, Integer ix) {
if (ix >= i1 && ix <= i2) return true;
return false;
}
public void showMessageBox(Object ttl, Object msg, DialogInterface.OnClickListener rt) {
new AlertDialog.Builder(activity)
.setMessage(msg.toString())
.setTitle(ttl.toString())
.setCancelable(false)
.setNeutralButton(android.R.string.ok, rt)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hisp, 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_hisp, container, false);
return rootView;
}
}
}

Because in onCreate() you have used
EditText textViewML = (EditText) findViewById(R.id.textViewML);
instead of
TextView txt = (TextView) findViewById(R.id.textViewML);
so you got problem. So you need to use after your setContentView() method.
TextView txt = (TextView) findViewById(R.id.textViewML);

Put in the onCreate :
TextView textViewML = (TextView) findViewById(R.id.textViewML);

The error was from
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Thanks a lot guys for pointing this out!

you are casting Textview to EditText dont do that
EditText textViewML = (EditText) findViewById(R.id.textViewML);
change it as
TextView textViewML = (TextView) findViewById(R.id.textViewML);

Exception is not your layout file it is in your java file you are casting TextView into EditText.
You can not Cast Super class in to sub class.
you can cast Sub class into Super Class.
You can Cast EditText into TextView but not TextView in to EditText.
Change this line
TextView txt = (TextView) findViewById(R.id.textViewML);
Thanx

Related

ListView with custom adapter is crashing after adding a new item? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Custom ListView Adapter Null Object Reference
(1 answer)
Closed 2 years ago.
I'm creating an app that makes inventaries for the restaurant of my parents. I've been working in the custom view that shows the name of the product and the quantity of it on the current inventary in a listView. Everything works fine until I add a new product to any inventary. After I add the product any time that I go to the that inventary the app crash.
This is visionInventario.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class visionInventario extends AppCompatActivity {
TextView tituloInventario;
static int positionCurrentInventario;
static InventarioListAdapter adapter1;
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list",null);
Type type = new TypeToken<ArrayList<Inventario>>(){}.getType();
Inventarios.InventariosActuales = gson.fromJson(json,type);
for(int i = 0; i < Inventarios.InventariosActuales.size();i++){
Inventarios.nombresInventarios.add(Inventarios.InventariosActuales.get(i).nombre);
}
if(Inventarios.InventariosActuales == null){
Inventarios.InventariosActuales = new ArrayList<>();
}
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(Inventarios.InventariosActuales);
editor.putString("task list",json);
editor.apply();
}
public void addProductoButton(View view){
Intent goToAddNewProducto = new Intent(this,addNewProducto.class);
startActivity(goToAddNewProducto);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vision_inventario);
//loadData();
tituloInventario = (TextView) findViewById(R.id.tituloInventario);
Intent thisIntent = getIntent();
positionCurrentInventario = thisIntent.getIntExtra("itemPosition",0);
tituloInventario.setText(Inventarios.nombresInventarios.get(positionCurrentInventario));
ListView listProductos = (ListView) findViewById(R.id.listaProductos);
adapter1 = new InventarioListAdapter(this,Inventarios.InventariosActuales.get(positionCurrentInventario).products);
listProductos.setAdapter(adapter1);
listProductos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent goToVisionProducto = new Intent(getApplicationContext(),visionProducto.class);
goToVisionProducto.putExtra("productPosition",position);
startActivity(goToVisionProducto);
}
});
}
}
This is addNewProducto.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
public class addNewProducto extends AppCompatActivity {
TextView nombreDelNuevoProducto;
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(Inventarios.InventariosActuales);
editor.putString("task list",json);
editor.apply();
}
public void AddNewProductoClick(View view){
producto nuevoProducto = new producto(nombreDelNuevoProducto.getText().toString());
Inventarios.InventariosActuales.get(visionInventario.positionCurrentInventario).addProduct(nuevoProducto);
visionInventario.adapter1.notifyDataSetChanged();
Toast.makeText(this,"¡Producto añadido!", Toast.LENGTH_SHORT).show();
saveData();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_producto);
nombreDelNuevoProducto = (TextView) findViewById(R.id.nombreProducto);
}
}
This is InventarioListAdapter.java
package com.DreamFactory.restaurantcontrol;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class InventarioListAdapter extends BaseAdapter {
Context context;
ArrayList<producto> arr;
public InventarioListAdapter(Context context, ArrayList<producto> arr) {
this.context = context;
this.arr = arr;
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(context).inflate(R.layout.adapter_view_layout, parent, false);
}
TextView quantity = (TextView)convertView.findViewById(R.id.existenciasInventarioVision);
TextView nameQ = (TextView) convertView.findViewById(R.id.productoInventarioVision);
quantity.setText(arr.get(position).cantidad);
nameQ.setText(arr.get(position).nombre);
return listItemView;
}
}
This is adapter_view_layout.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">
<LinearLayout
android:layout_width="409dp"
android:layout_height="729dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/productoInventarioVision"
android:gravity="center"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="66.6"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="33.3"
android:orientation="vertical">
<TextView
android:id="#+id/existenciasInventarioVision"
android:layout_width="match_parent"
android:layout_height="61dp"
android:gravity="center"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstrainLayout>
This is my LogCat when it crashes
2020-04-05 22:49:14.310 17301-17301/com.DreamFactory.restaurantcontrol E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.DreamFactory.restaurantcontrol, PID: 17301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.DreamFactory.restaurantcontrol.InventarioListAdapter.getView(InventarioListAdapter.java:52)

How to Save İmage from ViewPager?

My problem is that it always saves the same photo when I press the Save Button. I have more than 10 photos in my Viewpager, it just saves the first one, so I can't save what I want the photo,
I want to save the open photo.
I want the photo in the open window to be saved.
items.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"
android:id="#+id/gallery_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/layut"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:orientation="vertical"
android:weightSum="30">
<FrameLayout
android:id="#+id/wallpaper_preview_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/movie_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</RelativeLayout>
fragment_simple.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment.SimpleFragment">
<androidx.viewpager.widget.ViewPager
android:id="#+id/vivi_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/bSave"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:gravity="center"
android:layout_marginTop="150dp"
android:text="Save"
android:layout_alignParentStart="true"
android:textSize="24sp"
android:padding="0dp" />
</RelativeLayout>
SimpleFragment.java
package com.example.duvarlar.Fragment;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.duvarlar.Adapters.MyAdapter;
import com.example.duvarlar.Listeneer.IFirebaseLoadDone;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.example.duvarlar.Transformer.DeptPageTransformer;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A simple {#link Fragment} subclass.
*/
public class SimpleFragment extends Fragment implements IFirebaseLoadDone, ValueEventListener {
ViewPager viewPager;
MyAdapter adapter;
DatabaseReference movies;
IFirebaseLoadDone iFirebaseLoadDone;
Button save;
OutputStream outputStream;
public SimpleFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_simple, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
iFirebaseLoadDone = this;
loadMovie();
viewPager = (ViewPager) view.findViewById(R.id.vivi_pager);
save = (Button) view.findViewById(R.id.bSave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setDrawingCacheEnabled(true);
Bitmap bitmap = viewPager.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Android");//directory name of your choice
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-" + n + ".jpg";
File file = new File(newDir, fotoname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Saved to your folder" + fotoname, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
adapter = new MyAdapter(getContext(), movieList);
viewPager.setAdapter(adapter);
}
#Override
public void onFirebasLoadFailed(String message) {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<Movie> movieList = new ArrayList<>();
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
MyAdapter.java
package com.example.duvarlar.Adapters;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
public class MyAdapter extends PagerAdapter {
Context context;
List<Movie> movieList;
LayoutInflater inflater;
OutputStream outputStream;
public MyAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
((ViewPager)container).removeView((View)object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
final View view = inflater.inflate(R.layout.items,container,false);
final ImageView movie_image = (ImageView)view.findViewById(R.id.movie_image);
Picasso.get()
.load(movieList.get(position).getImage())
.fit()
.centerCrop()
.into(movie_image);
container.addView(view);
return view;
}
}

Stop reload () after a certain scroll

With this code, as I while scrolling, say 10%, disable web.reload (); And for one, as I variable String url of shouldOverrideUrlLoading endure beyond the example as above in a variable String XYvariable.
package ru.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
TextView TEXT;
String XYvariable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView web = (WebView) findViewById(R.id.webView);
web.loadUrl("http://example.com/string.html");
web.getSettings().setJavaScriptEnabled(true);
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
web.reload();
}
}, 1000, 1000);
web.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String Cur = (String) url.substring(23);
String Link = (String) url.substring(16,23);
String XY = (String) url; // Post varriable up in string XYvariable
setContentView(R.layout.vot);
TEXT = (TextView) findViewById(R.id.textView);
switch (Link){
case "id_user":
TEXT.setText(Cur+" / user");
break;
case "id_mess":
TEXT.setText(Cur + " / messages");
break;
}
return true;
}
});
}
public boolean onCreateOptionsMenu (Menu menu){
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ru.MainActivity">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
In advance thank you all, very much! ))

Android Spinner on activity other than starting activity

I'm having a bit of an issue, I'm working on a android app that requires a spinner to update a string to your spinner selection, I have it all working and everything, the problem is that I need the spinner on another activity than the starting activity but when I start the app with a different activity than the one with the spinner and activate the array adapter and listener at the same time I switch views to the one with the spinner, the spinner is empty with no choices. I can't for the life of me figure this out. PS, sorry about the weird variable names I get bored and instead of making a proper name I think of something on the spot and come back and change it later. PPS The name of the content view with the spinner is orderpage and the one I want to have start with the app is activity_main PPPS I cut out some methods I deemed irrelevant so there are some variables not used. I attached my code below:
package com.NIQUOLI.Deliveryapp;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.NIQUOLI.Deliveryapp.GMailSender;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Debug;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
public static boolean deeznuts = false;
public static String storenamestring;
public static String namesame;
public static String instructionsame;
public int choice = 0;
private Spinner spinner1;
private Button button = null;
String[] stores;
Spinner sp;
public void cont(View View){
deeznuts = true;
setContentView(R.layout.orderpage);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.orderpage);
button = (Button) findViewById(R.id.send_email);
super.onCreate(savedInstanceState);
sp = (Spinner) findViewById(R.id.sp);
stores = getResources().getStringArray(R.array.stores);
if (deeznuts = true){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,stores);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You selected"+stores[index], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
}
#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);
}
}
and of course my XML with the s[ommer:
<?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="vertical"
tools:context="com.NIQUOLI.Deliveryapp.SendMailTask" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="#string/order_page"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Space
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center_horizontal"
android:hint="#string/enter_your_name"
android:inputType="text" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/sp"
android:layout_width="388dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/instructions"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.34"
android:ems="10"
android:inputType="textMultiLine" />
<Button
android:id="#+id/send_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/send_order" />
</LinearLayout>
On the 6th line of the onCreate method in the first code sample, if(deeznuts = true) should be if(deeznuts == true).

Error using relative layout using code

I am getting java.lang.IllegalStateException while using relative layout using code. I know how to use relative layout using xml, but I have to use it using code only.
Here is my code:
package com.example.pr;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ProfessionalProfileTab extends Fragment
{
EditText regNumber,medCouncil,languages,degree,course,year,speciality,
experience_start_month,experience_end_month,designation,experience_company;
TextView regNumberText,medCouncilText,languagesText,degreeText,specialityText,experienceText;
ImageButton addDegree;
Button updateProfession;
Display display;
double width,height;
private int mYear, mMonth, mDay;
Context con;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
display = getActivity().getWindowManager().getDefaultDisplay();
width = MainActivity.Parentwidth;
height = MainActivity.Parentheight;
Log.d("Inside Professional Profile Fragment","ppsg");
Log.d("width",String.valueOf(width));
Log.d("height",String.valueOf(height));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.professional_profile_tab, container, false);
con = container.getContext();
final LinearLayout layout=(LinearLayout)view.findViewById(R.id.professionalProfileDetails);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
final RelativeLayout rlayout=(RelativeLayout)view.findViewById(R.id.reldegree) ;
final RelativeLayout.LayoutParams rparam=new RelativeLayout.LayoutParams(
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT) ;
final TextView degreeText=new TextView(con);
degreeText.setTag("degreeText");
degreeText.setText("degree:");
layout.addView(degreeText);
rlayout.addView(degreeText);
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(params);
degreeText.setLayoutParams(rparam);
final ImageButton addDegree=new ImageButton(con);
addDegree.setTag("addDegree");
addDegree.setImageResource(R.drawable.ic_launcher);
layout.addView(addDegree);
rlayout.addView(addDegree);
rparam.addRule(RelativeLayout.BELOW,addDegree.getId());
degreeText.setLayoutParams(params);
addDegree.setLayoutParams(rparam);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
}
Here is the xml version of what I want from my code:
<LinearLayout
android:id="#+id/professionalProfileDetails"
android:layout_width="320dp"
android:layout_height="200dp"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/reldegree"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/degreeText"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Degree Details"/>
<ImageButton
android:id="#+id/addDegree"
android:layout_toRightOf="#id/degreeText"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
</LinearLayout>
Here I want to set the image to the right of degreetext textField.
I have tried to search for a solution to this problem, but could not find any.
Can we use relative layout in the same way as we do in xml and set layout:toRightOf or toLeftOf or below etc using code for texts or images.
You are trying to add the same View to 2 different ViewGroups which is not possible.
layout.addView(degreeText);
rlayout.addView(degreeText);
Also, you are trying to position a View below itself.
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(rparam);
**Try this**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.demo.MainActivity" >
<RelativeLayout
android:id="#+id/layoutContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp" >
</RelativeLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
RelativeLayout layoutContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutContainer = (RelativeLayout)
findViewById(R.id.layoutContainer);
final TextView degreeText=new TextView(this);
degreeText.setId(1);
degreeText.setText("degree:");
layoutContainer.addView(degreeText);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, degreeText.getId());
final ImageButton addDegree=new ImageButton(this);
addDegree.setImageResource(R.drawable.ic_launcher);
addDegree.setLayoutParams(params);
layoutContainer.addView(addDegree);
}
}

Categories

Resources