How to change TextView in fragment in on create or when a button is called - onclick

Almost 10 hours am I searching for an answer. Why my app crashes when i launch it.
What I realy want is a function that when I click OK on Edittext, text will be written on Text view. But first just hat to set text in on create in class that extence fragment.
package youtube.demo.youtubedemo.Fragments.Calculator_list;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import youtube.demo.youtubedemo.R;
public class Calculator_list extends Fragment {
View view;
FragmentManager fragmentManager;
public Calculator_list() {
}
TextView Damage1pise;
EditText Damage1beri;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_calculator_list, container, false);
Damage1beri = (EditText) view.findViewById(R.id.Game1_read_dmg_list_Player1);
Damage1pise = (TextView)view.findViewById(R.id.Game1_writen_dmg_list_Player1);
Damage1pise.setText("123");
return view;
}
public TextView Returnelement ()
{
return Damage1pise;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Damage1pise = (TextView)getView().findViewById(R.id.Game1_writen_dmg_list_Player1);
Damage1pise.setText("1234");
super.onCreate(savedInstanceState);
}
}
What I realy want is a funcction that when I click OK on Edittext, text will be written on Text view
public void OnButton1click(View v)
{
Damage1.settext(v.text)
// This is hard coded, First I want to set text on create then go on whit the code
}
Here are the errors.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: youtube.demo.youtubedemo, PID: 2736
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at youtube.demo.youtubedemo.Fragments.Calculator_list.Calculator_list.onCreate(Calculator_list.java:47)
at android.app.Fragment.performCreate(Fragment.java:2335)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:949)
at android.app.BackStackRecord.setLastIn(BackStackRecord.java:857)
at android.app.BackStackRecord.calculateFragments(BackStackRecord.java:897)
at android.app.BackStackRecord.run(BackStackRecord.java:727)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

On this line of your showed code, both methods, certify yourself you have a blank space between (TextView) and the end of the sentence, like below:
Damage1pise = (TextView) getView().findViewById(R.id.Game1_writen_dmg_list_Player1);
Also, certify yourself you have a textview on your invoked layout file xml with name Game1_writen_dmg_list_Player1, because the error is been raised by a null reference, i.e.: you're invoking a not found element (maybe written with two ts?).

Related

Android upload to Firebase Bucket with SchedulerAPI

Background:
I am using Firebase for my Android App Development This app require every user upload an object from their phone to the bucket/ Firebase Storage once a day. So, I want to make the process of "object upload" as a background service with JobSchedulerAPI.
I have copied source code from Firebase and a youtube video related to Job Scheduler. But when I clicked the button, the app stopped immediately.
MainActivity.Java
package com.scheduleupload;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final ComponentName mComponentName = new ComponentName(this, Scheduler.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JobInfo info = new JobInfo.Builder(123, mComponentName)
.setPeriodic(15 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
});
}
}
Scheduler.Java
package com.scheduleupload;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.net.Uri;
import android.util.Log;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class Scheduler extends JobService {
private static final String TAG = "ExampleJobService";
private boolean jobCancelled =false;
private StorageReference mStorage;
mStorage = FirebaseStorage.getInstance().getReference();
String myUri = "content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3D693";
final Uri uri = Uri.parse(myUri);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job Started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(JobParameters params) {
new Thread(new Runnable() {
#Override
public void run() {
filepath.putFile(uri);
}
}).start();
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
Thx a lot for spending such a long while to read my question
crash log:
05-07 21:53:52.775 6261-6261/com.scheduleupload E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.scheduleupload, PID: 6261
java.lang.IllegalArgumentException: No such service ComponentInfo{com.scheduleupload/com.scheduleupload.Scheduler}
at android.os.Parcel.readException(Parcel.java:2008)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:180)
at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
at com.scheduleupload.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Have found solution, it is because the Scheduler can't access to some of the storage. Simply change to file location to somewhere it is accessible by Job Scheduler can solve the problem

App crashes on clicking on textView in fragment

I'm creating an app in which there are three tab activity.In tab Three i have a textview name as login text whenever user click on this text a new activity should be opened but app crashes when we click on this.
I have done many research to resolve this problem but i'm unable to resolve at last i'm here for the solution of my problem Please help.
Thanks in advance.
This is my loginActivity.
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class loginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText email_Id;
private EditText password;
private TextView sign_Up;
private Button sign_In;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth=FirebaseAuth.getInstance();
// if(firebaseAuth.getCurrentUser()!=null){
// directly start user profile activity
// finish();
// startActivity(new Intent(this,userProfileActivity.class));
//}
progressDialog=new ProgressDialog(this);
email_Id=(EditText)findViewById(R.id.email_id);
password=(EditText)findViewById(R.id.password);
sign_In=(Button)findViewById(R.id.sign_In);
sign_Up=(TextView)findViewById(R.id.sign_up);
sign_In.setOnClickListener(this);
sign_Up.setOnClickListener(this);
}
private void user_Login(){
String email=email_Id.getText().toString().trim();
String pass_word=password.getText().toString().trim();
if(TextUtils.isEmpty(email)){
// email is empty
Toast.makeText(this,"please enter email",Toast.LENGTH_SHORT).show();
return;// to stop the function from executation.
}
if(TextUtils.isEmpty(pass_word)){
// email is empty
Toast.makeText(this,"please enter password",Toast.LENGTH_SHORT).show();
return;
}
// here if everything ok the user will be register
progressDialog.setMessage("Registering User,please wait...");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,pass_word)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()){
// start user profile activity
finish();
startActivity(new Intent(getApplicationContext(),userProfileActivity.class));
}
}
});
}
#Override
public void onClick(View view) {
if (view==sign_In){
// start user profile activity
user_Login();
}
if(view==sign_Up){
// go to registeration page
finish();
startActivity(new Intent(this,FragmentThree.class));
}
}
}
this is declaration
This is my login method
The following line in your code throws the exception:
sign_Up.setOnClickListener(this);
The problem is, that sign_Up is null!
You set sign_Up with: sign_Up=(TextView)findViewById(R.id.sign_up);
Make sure, that setContentView(R.layout.activity_login); (activity_login) is the right one. If, try to clean and rebuild your project and try again.
Update: It is possible, that sign_up should be a button? If, you make a wrong cast!
Change the TextView in this line:
sign_Up=(TextView)findViewById(R.id.sign_up);
to Button, like this:
sign_Up=(Button)findViewById(R.id.sign_up);

On Android how to call from TextView inside a fragment?

I am trying to call when someone tap or click on a number which in a TextView.
I have added permission in Android AndroidMainfest.xml
<uses-permission android:name="android.permission.CALL_PHONE" />
Also I have set the TextView android:clickable="true"
I am very new in Android development so please Help me.
I am sorry for my bad English.
Here is My code AboutDeveloper.java
package com.rupomkhondaker.sonalibank;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class AboutDeveloper extends Fragment {
public AboutDeveloper(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final TextView tv_phone = (TextView)getActivity().findViewById(R.id.devMobile);
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String phone_no= tv_phone.getText().toString().replaceAll(":", "");
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phone_no));
startActivity(callIntent);
}
});
View rootView = inflater.inflate(R.layout.fragment_developer, container, false);
return rootView;
}
}
ERROR LOG
09-20 20:28:05.852 622-622/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.rupomkhondaker.sonalibank.AboutDeveloper.onCreateView(AboutDeveloper.java:22)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
at android.app.BackStackRecord.run(BackStackRecord.java:635)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Replace your code by this code and tell me what is the output.
public class AboutDeveloper extends Fragment {
public AboutDeveloper(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_developer, container, false);
final TextView tv_phone = (TextView)v.findViewById(R.id.devMobile);
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try
{
String uri = "tel:"+tv_phone.getText().toString();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
}
catch(Exception e) {
Toast.makeText(getActivity(),"Your call has failed...",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
return v;
}
Since you were getting
java.lang.NullPointerException
at com.rupomkhondaker.sonalibank.AboutDeveloper.onCreateView(AboutDeveloper.java:22)
it meant that it was not able to find the view element.

Fetching Parse objects into Arraylist using AsyncTask

I am trying to fetch bunch of parse objects into an Arraylist based on descending order of "createdAt". I am using fragments in my app, which has a fragment called "Recents".
Initially, I was able to store the data in a hashmap and add each of them to the array list and display them as a listview. I was able to see the list on my recents tab.
But, I realized it shouldnt be running on the main thread, so I found Async Task and i tried to implement the same. But I am unable to view any Listview on my screen.
Code for AsyncTask:
package com.astuetz.viewpager.extensions.sample;
/**
* Created by Shankar S on 10-06-15.
*/
import android.os.AsyncTask;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class getBooks extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {
RecentsCardFragment container;
public getBooks(RecentsCardFragment f){
this.container = f;
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
final ArrayList<HashMap<String, String>> book_items = new ArrayList<>();
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery(params[0]);//params[0] refers to the class name(a String) from which
query.orderByDescending("createdAt"); //parse object is to be queried. In our case, it is "Posted"
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
for (ParseObject book : parseObjects) {
HashMap<String, String> test = new HashMap<>();
String dept = book.getString("Department");
String title = book.getString("Title");
String author = book.getString("Author");
Number price_num = book.getNumber("Price");
String price = String.valueOf(price_num);
String place = book.getString("Place");
String desp = book.getString("Description");
test.put("dept", dept);
test.put("title", title);
test.put("author", author);
test.put("price", price);
test.put("place", place);
test.put("description", desp);
book_items.add(test);
}
}
}
});
} catch (Exception ex) {
}
return book_items;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
container.showProgress();
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> books) {
super.onPreExecute();
if(RecentsCardFragment.items.size()>0)
{
RecentsCardFragment.items.clear();
}
RecentsCardFragment.items.addAll(books);
container.hideProgress();
}
}
and the code for RecentsFragment:
/*
* Copyright (C) 2013 Andreas Stuetz <andreas.stuetz#gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.astuetz.viewpager.extensions.sample;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ListView;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class RecentsCardFragment extends Fragment
{
ListView recentsList;
getBooks task;
private ProgressDialog pdia;
/*
array list of hashmaps that's going to hold all the data
fetch the data from parse and load it onto this
Each hashmap represents one post.
*/
static ArrayList<HashMap<String,String>> items = new ArrayList<>();
protected void startBookfetch()
{
task = new getBooks(this);
task.execute("Posted");
}
//sample hashmaps
HashMap<String,String> test1 = new HashMap<>();
HashMap<String,String> test2 = new HashMap<>();
public void showProgress()
{
pdia = new ProgressDialog(getActivity());
pdia.setMessage("Loading...");
pdia.show();
}
public void hideProgress(){
pdia.dismiss();
}
public static RecentsCardFragment newInstance() {
RecentsCardFragment f = new RecentsCardFragment();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recents_card,container,false);
ViewCompat.setElevation(rootView,50);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
recentsList = (ListView)getActivity().findViewById(R.id.recents_list);
startBookfetch();//Calls the async task getBooks to download books from Parse
RecentsAdapter adapter = new RecentsAdapter(getActivity().getApplicationContext(), items);
recentsList.setAdapter(adapter);
}
}
Please help me out! I am not able to view progress Dialog or the listview.
I want the async task to be run when activity is created, not on any button click.
I am trying async task for the first time.
I just realized that I dont need to async task for a task that is already being handled at background. The findinBackground method I use for querying data from Parse already does the task in background only. So, this is absolutely not necessary.
I need to keep the code same as it was earlier.

Adding Gridview to fragment it's crashing

I'm following a tutorial and trying to build in a grid view into my fragment and every time I launch the app it crashes. I opened up LogCat and it gives me nothing... Can someone help me find out what I can do to get this to display correctly and not crash the app? Thank you!!!
Below I've included my Main Activity, GridView Adapter and Fragment...
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
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
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private Char
Sequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set the first title
mTitle = "Inventory";
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
// Remove shadow under actionbar
getSupportActionBar().setElevation(0);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new Inventory_Fragment();
mTitle = getString(R.string.title_section1);
break;
case 1:
objFragment = new Orders_Fragment();
mTitle = getString(R.string.title_section2);
break;
case 2:
objFragment = new Cart_Fragment();
mTitle = getString(R.string.title_section3);
break;
case 3:
objFragment = new Settings_Fragment();
mTitle = getString(R.string.title_section4);
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.inventory_layout, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
// MARK: - Helpers
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
GridViewAdapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Created by kenbarlow on 5/20/15.
*/
public class GridViewAdapter extends BaseAdapter {
private Context context;
public GridViewAdapter(Context context) {
context = context;
}
private int[] icons = {
// Temporary
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
R.drawable.image11,
R.drawable.image12,
R.drawable.image13,
R.drawable.image14,
R.drawable.image15,
R.drawable.image16,
R.drawable.image17
};
#Override
public int getCount() {
return icons.length;
}
#Override
public Object getItem(int position){
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(10, 10, 10, 10);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(icons[position]);
return imageView;
}
}
Inventory_Fragment --- I Feel like the problem is in here but I'm not sure.
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.GridView;
/**
* Created by kenbarlow on 5/19/15.
*/
public class Inventory_Fragment extends Fragment {
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.inventory_layout, container, false);
GridView gridview = (GridView) getActivity().findViewById(R.id.gridview);
gridview.setAdapter(new GridViewAdapter(this));
return rootView;
}
}
I guess your are trying to find a gridview in the activity's layout, which is wrong because the gridview is in the Fragment's layout.
Please change in your fragment code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.inventory_layout, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
if(gridview != null){
gridview.setAdapter(new GridViewAdapter(getActivity()));
}
return rootView;
}
If it's not the cause of the problem, please post a stacktrace when the crash happen (it should have already been done).
I have not looked at all the code yet. I reviewed GridViewAdapter and Inventory_Fragment.
Remove getItemId method in GridViewAdapter. You don't use it anyway. It is possible that the BaseAdapter is referencing it, and returning it null from that method may crash the adapter.
Code suggestion, return an item for this method:
#Override
public Object getItem(int position){
return icons[position];
}
LogCat and it gives me nothing...
if literally nothing, try to reset LogCat.
as i see in these lines
rootView = inflater.inflate(R.layout.inventory_layout, container, false);
GridView gridview = (GridView) getActivity().findViewById(R.id.gridview);
you are inflating and makeing rootView to find your inner layouts. so instead of getActivity() in second line use your rootView.
and remember to put your gridView layout inside inventory_layout
I am not sure if it is the only issue or not, but this one looks a bit wrong.
In your Inventory_Fragment class:
gridview.setAdapter(new GridViewAdapter(this));
You should change it to this:
gridview.setAdapter(new GridViewAdapter(getActivity()));
Also please upload your layouts and/or logcat report here. It is hard to go through the code like this.

Resources