这是我的代码,应用程序将显示cpu /内存信息和其他内容但在启动时崩溃:
package eu.lucazanini.swipeviews;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
TextView textOut;
private TextView cpuInfo;
private TextView memoryInfo;
// Notification code
private static final int SIMPLE_NOTIFICATION_ID = 1;
NotificationManager mNotificationManager;
// fine
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Readcpuinfo
TextView CPUinfo = (TextView) findViewById(R.id.CPUinfo);
CPUinfo.setText(getCPUinfo());
TextView Memoryinfo = (TextView) findViewById(R.id.memoryinfo);
Memoryinfo.setText(getMemoryInfo());
//fine readcpuinfo
// Notification code
mNotificationManager = (NotificationManager) `getSystemService(Context.NOTIFICATION_SERVICE);`
View btnradio_hindi = findViewById(R.id.radio_hindi);
// fine
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
}
/// Inizio creazione funzioni
private String getMemoryInfo(){
ProcessBuilder cmd;
String result = new String();
try{
String[] args = {"/system/bin/cat", "/proc/meminfo"};
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while(in.read(re) != -1){
System.out.println(new String(re));
result = result + new String(re);
}
in.close();
} catch(IOException ex){
ex.printStackTrace();
}
return result;
}
private String getCPUinfo()
{
ProcessBuilder cmd;
String result="";
try{
String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while(in.read(re) != -1){
System.out.println(new String(re));
result = result + new String(re);
}
in.close();
} catch(IOException ex){
ex.printStackTrace();
}
return result;
}
public Boolean execCommands(String... command) {
try {
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
for(int i = 0; i < command.length; i++) {
os.writeBytes(command[i] + "\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (IOException e) {
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
/**
* A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a
* fragment representing an object in the collection.
*/
public class CollectionPagerAdapter extends FragmentStatePagerAdapter {
final int NUM_ITEMS = 3; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return NUM_ITEMS;
}
@Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
case 2:
tabLabel = getString(R.string.label3);
break;
}
return tabLabel;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
return rootView;
}
}
public void onRadioButtonClicked(View view) {
((RadioButton) view).isChecked();
// Check which radio button was clicked
// switch(view.getId()) {
// case R.id.radio_hindi:
// if (checked)
switch (view.getId())
{
case R.id.radio_hindi:
String[] commands = {
"echo 3 > /proc/sys/vm/drop_caches",
"cat /proc/meminfo | awk 'NR == 2'"
};
sendSimpleNotification();
Toast.makeText(this, "Hai liberato memoria! Hai: " + `Runtime.getRuntime().freeMemory() + "", Toast.LENGTH_LONG).show();`
execCommands(commands);
String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> `/sdcard/foo.txt";`
execCommands(commandText.split("\n"));
break;
case R.id.radio_english:
String[] commands1 = {"echo ondemand > `/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"`,
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands1);
sendSimpleNotificationOndemand();
Toast.makeText(this, "Hai selezionato il governor Ondemand", `Toast.LENGTH_LONG).show();`
break;
case R.id.interactive_btn:
String[] commands2 = {"echo interactive > `/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",`
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands2);
sendSimpleNotificationInteractive();
Toast.makeText(this, "Hai selezionato il governor: Interactive", `Toast.LENGTH_LONG).sho`w();
break;
case R.id.conservative_btn:
String[] commands3 = {"echo conservative > `/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor",`
"/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_governor",
"/sys/devices/system/cpu/cpu3/cpufreq/scaling_governor"};
execCommands(commands3);
sendSimpleNotificationConservative();
Toast.makeText(this, "Hai selezionato il governor: Conservative", `Toast.LENGTH_LONG).show();`
break;
}
}
protected void cancelSimpleNotification() {
mNotificationManager.cancel(SIMPLE_NOTIFICATION_ID);
}
private void sendSimpleNotification() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Boost RAM");
notificationBuilder.setContentText("Memoria libera: "+ `Runtime.getRuntime().freeMemory() + "bytes");`
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Memoria liberata con successo");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
// Notification per il governor ondemand
private void sendSimpleNotificationOndemand() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Ondemand");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Ondemand settato");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
//Notification per il governor interactive
private void sendSimpleNotificationInteractive() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Interactive");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Interactive settato");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
//Notification per il governor conservative
private void sendSimpleNotificationConservative() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
MainActivity.this);
// Titolo e testo della notifica
notificationBuilder.setContentTitle("Governor Changed");
notificationBuilder.setContentText("Hai selezionato il governor Conservative");
// Testo che compare nella barra di stato non appena compare la notifica
notificationBuilder.setTicker("Governor Conservative settato");
// Data e ora della notifica
notificationBuilder.setWhen(System.currentTimeMillis());
// Icona della notifica
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
// Creiamo il pending intent che verrà lanciato quando la notifica
// viene premuta
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
// Impostiamo il suono, le luci e la vibrazione di default
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(SIMPLE_NOTIFICATION_ID,
notificationBuilder.build());
}
}
我不知道为什么但总是在启动时崩溃:(任何建议? 日志:
05-27 00:14:09.933: E/AndroidRuntime(6243): FATAL EXCEPTION: main
05-27 00:14:09.933: E/AndroidRuntime(6243): java.lang.RuntimeException: Unable to start `activity ComponentInfo{eu.lucazanini.swipeviews/eu.lucazanini.swipeviews.MainActivity}: `java.lang.NullPointerException
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2357)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.access$600(ActivityThread.java:153)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247`)
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.os.Handler.dispatchMessage(Handler.java:99)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.os.Looper.loop(Looper.java:137)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.main(ActivityThread.java:5226)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `java.lang.reflect.Method.invokeNative(Native Method)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `java.lang.reflect.Method.invoke(Method.java:511)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `dalvik.system.NativeStart.main(Native Method)`
05-27 00:14:09.933: E/AndroidRuntime(6243): Caused by: java.lang.NullPointerException
05-27 00:14:09.933: E/AndroidRuntime(6243): at `eu.lucazanini.swipeviews.MainActivity.onCreate(MainActivity.java:56)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.Activity.performCreate(Activity.java:5104)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)`
05-27 00:14:09.933: E/AndroidRuntime(6243): at `android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)`
05-27 00:14:09.933: E/AndroidRuntime(6243): ... 11 mor
e
如果需要其他信息请告诉我。非常感谢你
java的第56行:
CPUinfo.setText(getCPUinfo());
我有4 xml,因为我有一个swipeview。 main.xml,tab1,tab2和tab3.xml。 main.xml中:
<android.support.v4.view.ViewPager `xmlns:android="http://schemas.android.com/apk/res/android"`
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
tab1.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="CHANGE GOVERNOR"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF8000"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Change the CPU Governor: "
android:textColor="#00AEEF"
tools:ignore="HardcodedText" />
<RadioButton
android:id="@+id/radio_english"
android:layout_width="201dp"
android:layout_height="55dp"
android:onClick="onRadioButtonClicked"
android:text="OnDemand"
tools:ignore="HardcodedText" />
<RadioButton
android:id="@+id/interactive_btn"
android:layout_width="200dp"
android:layout_height="55dp"
android:onClick="onRadioButtonClicked"
android:text="Interactive"
tools:ignore="HardcodedText" />
<RadioButton
android:id="@+id/conservative_btn"
android:layout_width="200dp"
android:layout_height="55dp"
android:layout_gravity="fill"
android:onClick="onRadioButtonClicked"
android:text="Conservative"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/AndroidCPUInfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Android CPU Info.:"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/CPUinfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:ignore="SelectableText" />
</RadioGroup>
tab2.xml:
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="BOOST RAM"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF8000"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/textView1"
android:layout_width="296dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Boost your RAM memory and drop the cache to speed up your phone! Click `the Radio Button."`
android:textColor="#00AEEF"
tools:ignore="HardcodedText" />
<RadioButton
android:id="@+id/radio_hindi"
android:layout_width="match_parent"
android:layout_height="64dp"
android:onClick="onRadioButtonClicked"
android:text="Drop the cache and boost your RAM"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/memo_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Memory Info:"
android:textColor="#0000FF"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/memoryinfo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:ignore="SelectableText" />
</RadioGroup>
和tab3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="10dp"
android:text="Version: 1.0.0"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="10dp"
android:text="Author: Davide Dellai"
tools:ignore="DuplicateIds,HardcodedText" />
<TextView
android:id="@+id/textView3"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginLeft="10dp"
android:autoLink="email"
android:text="Email id: name.surname@gmail.com"
tools:ignore="HardcodedText" />
</LinearLayout>
答案 0 :(得分:3)
这是因为您的R.id.CPUinfo
TextView和R.id.memoryinfo
TextView没有驻留在R.layout.main
中,您应该在适当的Fragment
onCreateView
中进行此调用
示例:
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
if (tabLayout == R.layout.tab1) {
TextView CPUinfo = (TextView) rootView.findViewById(R.id.CPUinfo);
CPUinfo.setText(getCPUinfo());
TextView Memoryinfo = (TextView) rootView.findViewById(R.id.memoryinfo);
Memoryinfo.setText(getMemoryInfo());
}
return rootView;
}
}