2017-01-08 15 views
0

私はアンドロイドアプリを作成しています。メインレイアウトには3つの画像ボタンがあり、クリックすると新しいアクティビティを開く必要があります。ImageButtonで新しいアクティビティを開く

私は、アプリケーションを実行し、それらを押して、アプリが粉砕。

MainActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert); 
    ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace); 
    ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather); 

    //Open Weather Activity 
    if (weatherbtn.isPressed() == true) { 
     weatherbtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View arg0) { 
       Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class); 
       startActivity(intent); 
      } 

     }); //Open Currency Activity 
    }else if (converterbtn.isPressed() == true) { 
     converterbtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View arg0) { 
       Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class); 
       startActivity(intent1); 
      } 
     });//Open Places Activity 
    } else if (placesbtn.isPressed()) { 
     placesbtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View arg0) { 
       Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class); 
       startActivity(intent1); 
      } 
     }); 
    } 
} 

たManifest.xml

<activity android:name=".CurrencyConverter_MainActivity"/> 
<activity android:name=".weather_mainActivity"/> 

それがなぜ起こるか任意のアイデア:これは私が使用しているコードのですか? 他のすべての記事はでチェックしていますが、この方法ではやっていますが、私の場合はうまくいきません。

Androidのモニターログ

01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM 


               --------- beginning of crash 
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56) 
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540 
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3 

Weather_MainActivity.java

package com.android.example.cwapp; 


import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.graphics.drawable.Drawable; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.Bundle; 
import android.provider.Settings; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.ProgressBar; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.squareup.okhttp.Call; 
import com.squareup.okhttp.Callback; 
import com.squareup.okhttp.OkHttpClient; 
import com.squareup.okhttp.Request; 
import com.squareup.okhttp.Response; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.IOException; 

import butterknife.ButterKnife; 
import butterknife.InjectView; 


public class weather_mainActivity extends AppCompatActivity { 


public static final String TAG = weather_mainActivity.class.getSimpleName(); 

private CurrentWeather mCurrentWeather; 

LocationManager locationManager; 

@InjectView(R.id.timeLabel) TextView mTimeLabel; 
@InjectView(R.id.temperatureLabel)TextView mTemperatureLabel; 
@InjectView(R.id.humidityValue)TextView mHumidityValue; 
@InjectView(R.id.precipValue)TextView mPrecipValue; 
@InjectView(R.id.summaryLabel)TextView mSummaryLabel; 
@InjectView(R.id.iconImageView)ImageView mIconImageView; 
@InjectView(R.id.refreshImageView)ImageView mRefreshImageView; 
@InjectView(R.id.progressBar)ProgressBar mProgressBar; 
@InjectView(R.id.locationLabel)TextView mLocation; 

public double latitude /*= 34.7720*/; 
public double longitude /*= 32.4297*/; 

//Location Manager 
private boolean checkLocation() { 
    if (!isLocationEnabled()) 
     showAlert(); 
    return isLocationEnabled(); 
} 

private void showAlert() { 
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
    dialog.setTitle("Enable Location") 
      .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + 
        "use this app") 
      .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivity(myIntent); 
       } 
      }) 
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
       } 
      }); 
    dialog.show(); 
} 
private boolean isLocationEnabled() { 
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || 
      locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
} 

private final LocationListener locationListenerBest = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     longitude = location.getLongitude(); 
     latitude = location.getLatitude(); 
    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 

    @Override 
    public void onProviderEnabled(String s) { 

    } 

    @Override 
    public void onProviderDisabled(String s) { 

    } 
}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ButterKnife.inject(this); 

    mProgressBar.setVisibility(View.INVISIBLE); 



    mRefreshImageView.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      getForecast(latitude, longitude); 
     } 
    }); 

    getForecast(latitude, longitude); 

    Log.d(TAG, "Main UI code is running!"); 
} 

private void getForecast(double latitude, double longitude) { 
    String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961"; 
    String forecastUrl = "https://api.forecast.io/forecast/" + apiKey + 
      "/" + latitude + "," + longitude; 

    if (isNetworkAvailable()) { 
     toggleRefresh(); 

     OkHttpClient client = new OkHttpClient(); 
     Request request = new Request.Builder() 
       .url(forecastUrl) 
       .build(); 

     Call call = client.newCall(request); 
     call.enqueue(new Callback() { 
      @Override 
      public void onFailure(Request request, IOException e) { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         toggleRefresh(); 
        } 
       }); 
       alertUserAboutError(); 
      } 

      @Override 
      public void onResponse(Response response) throws IOException { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         toggleRefresh(); 
        } 
       }); 

       try { 
        String jsonData = response.body().string(); 
        Log.v(TAG, jsonData); 
        if (response.isSuccessful()) { 
         mCurrentWeather = getCurrentDetails(jsonData); 
         runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           updateDisplay(); 
          } 
         }); 
        } else { 
         alertUserAboutError(); 
        } 
       } catch (IOException e) { 
        Log.e(TAG, "Exception caught: ", e); 
       } catch (JSONException e) { 
        Log.e(TAG, "Exception caught: ", e); 
       } 
      } 
     }); 
    } else { 
     Toast.makeText(this, getString(R.string.network_unavailable_message), 
       Toast.LENGTH_LONG).show(); 
    } 
} 

private void toggleRefresh() { 
    if (mProgressBar.getVisibility() == View.INVISIBLE) { 
     mProgressBar.setVisibility(View.VISIBLE); 
     mRefreshImageView.setVisibility(View.INVISIBLE); 
    } else { 
     mProgressBar.setVisibility(View.INVISIBLE); 
     mRefreshImageView.setVisibility(View.VISIBLE); 
    } 
} 

private void updateDisplay() { 
    float temp = mCurrentWeather.getTemperature(); 
    String temp2 = Float.toString((temp - 32) * (5/9)); 
    mTemperatureLabel.setText(temp2 + ""); 
    mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be"); 
    mHumidityValue.setText(mCurrentWeather.getHumidity() + ""); 
    mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%"); 
    mSummaryLabel.setText(mCurrentWeather.getSummary()); 
    mLocation.setText(mCurrentWeather.getTimeZone()); 


    Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId()); 
    mIconImageView.setImageDrawable(drawable); 
} 

private CurrentWeather getCurrentDetails(String jsonData) throws JSONException { 
    JSONObject forecast = new JSONObject(jsonData); 
    String timezone = forecast.getString("timezone"); 
    Log.i(TAG, "From JSON: " + timezone); 

    JSONObject currently = forecast.getJSONObject("currently"); 

    CurrentWeather currentWeather = new CurrentWeather(); 
    currentWeather.setHumidity(currently.getDouble("humidity")); 
    currentWeather.setTime(currently.getLong("time")); 
    currentWeather.setIcon(currently.getString("icon")); 
    currentWeather.setPrecipChance(currently.getDouble("precipProbability")); 
    currentWeather.setSummary(currently.getString("summary")); 
    currentWeather.setTemperature(currently.getDouble("temperature")); 
    currentWeather.setTimeZone(timezone); 

    Log.d(TAG, currentWeather.getFormattedTime()); 

    return currentWeather; 
} 


private boolean isNetworkAvailable() { 
    ConnectivityManager manager = (ConnectivityManager) 
      getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = manager.getActiveNetworkInfo(); 
    boolean isAvailable = false; 
    if (networkInfo != null && networkInfo.isConnected()) { 
     isAvailable = true; 
    } 

    return isAvailable; 
} 

private void alertUserAboutError() { 
    AlertDialogFragment_weather dialog = new AlertDialogFragment_weather(); 
    dialog.show(getFragmentManager(), "error_dialog"); 
} 

};

RUNログイン

01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory) 
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2 
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2 
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory) 
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2 
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed! 
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory) 
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2 
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property 
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0 
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240 
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310 
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580 
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380 
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700 
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main 
               Process: com.android.example.cwapp, PID: 5641 
               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference 
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                at android.os.Handler.dispatchMessage(Handler.java:102) 
                at android.os.Looper.loop(Looper.java:148) 
                at android.app.ActivityThread.main(ActivityThread.java:5417) 
                at java.lang.reflect.Method.invoke(Native Method) 
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference 
                at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36) 
                at android.app.Activity.performCreate(Activity.java:6237) 
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  
                at android.app.ActivityThread.-wrap11(ActivityThread.java)  
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  
                at android.os.Handler.dispatchMessage(Handler.java:102)  
                at android.os.Looper.loop(Looper.java:148)  
                at android.app.ActivityThread.main(ActivityThread.java:5417)  
                at java.lang.reflect.Method.invoke(Native Method)  
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020 
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104) 
+0

問題はplaces_mactactivityクラスにあります。コードを投稿してください。 –

+0

01-09 21:30:09.115 5641-5641 /? E/AndroidRuntime:致命的例外:メイン プロセス:com.android.example.cwapp、PID:5641 java.lang.RuntimeException:アクティビティを開始できませんComponentInfo {com.android.example.cwapp/com.android.example.cwapp .Places_mainActivity}:java.lang.NullPointerException:ヌルオブジェクトリファレンスで仮想メソッド 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'を呼び出そうとしました –

答えて

0

は、あなたがあなたのスタックトレースを表示する必要があります。この

<activity android:name=".CurrencyConverter_MainActivity"/> 
<activity android:name=".weather_mainActivity"/> 
<activity android:name=".CurrentWeather"/> 
+0

男は間違ったコードを投稿しました。 "weather_mainActivity.class"はそこにあり、.CurrentWeather.classはありません。 – noel293

+0

weather_mainActivity.classに.xmlファイルを指定してください。多分それに問題があるかもしれません。 – ash12

+0

あなたは今見ていることができますか? – noel293

0

ようなあなたのmainfestでCurrentWeather.classアクティビティを追加し、それが原因だ場合、あなたはわからないView.OnClickListnerを、必要はありません。それだけでなく、weatherbtn.setOnClickListener(新しいOnClickListener(){...

これ以外に、あなたの呼び出し方法については何も問題はありませんアクティビティ。

+0

私はビューを削除します。私はエラーが発生します... – noel293

+0

ああ、おかしい...大丈夫、まあ、そうすべきではないので、スタックトレースを共有できますか?これは副次的な問題であるため、私が言ったことを元に戻して、最初の問題のために元のスタックトレースを共有することができます。 – Spider

+0

今投稿しました! – noel293

関連する問題