2017-04-03 103 views
-2

我構建了一個應用程序來使用json解析和顯示來自MySQL的數據。我正在使用導航器的選項卡式活動。當我構建的apk沒有錯誤。但是當我運行我的應用程序時,我收到一個錯誤,因爲不幸的是,M-jadwal已經停止。不幸的是,應用程序m-jadwal已停止

項目文件:https://drive.google.com/file/d/0B9286Ffx-sgybkVmZXVpQV8zZFk/view?usp=sharing

這裏是我的代碼文件:

搖籃應用

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 25 
    buildToolsVersion "25.0.2" 
    defaultConfig { 
     applicationId "com.example.lamberto.m_jadwal" 
     minSdkVersion 15 
     targetSdkVersion 25 
     versionCode 1 
     versionName "1.0" 
     testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
    } 
    buildTypes { 
     release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 

dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:25.3.1' 
    compile 'com.android.support:design:25.3.1' 
    testCompile 'junit:junit:4.12' 
    compile 'com.android.support:recyclerview-v7:25.3.1' 
    compile 'com.android.support:cardview-v7:25.3.1' 
    compile 'com.android.support:design:25.3.1' 
} 

MainActivity.java

package com.example.lamberto.m_jadwal; 

import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.support.v4.widget.SwipeRefreshLayout; 
import android.support.design.widget.TabLayout; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.os.Bundle; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.widget.Toast; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.View; 
import android.view.ViewGroup; 

import android.widget.TextView; 

public class MainActivity extends AppCompatActivity { 


    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds 
    public static final int CONNECTION_TIMEOUT = 10000; 
    public static final int READ_TIMEOUT = 15000; 
    private RecyclerView mRVFishPrice; 
    private AdapterFish mAdapter; 
    SwipeRefreshLayout mSwipeRefreshLayout; 

    private SectionsPagerAdapter mSectionsPagerAdapter; 

    /** 
    * The {@link ViewPager} that will host the section contents. 
    */ 
    private ViewPager mViewPager; 


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

     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     // Create the adapter that will return a fragment for each of the three 
     // primary sections of the activity. 
     mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

     // Set up the ViewPager with the sections adapter. 
     mViewPager = (ViewPager) findViewById(R.id.container); 
     mViewPager.setAdapter(mSectionsPagerAdapter); 

     TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
     tabLayout.setupWithViewPager(mViewPager); 
     // Refresh Start 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_jadwal_batal); 
     // Swipe Refresh Layout 
     mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swifeRefresh); 
     mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 
      @Override 
      public void onRefresh() { 
       new AsyncFetch().execute(); 
      } 
     }); 
     //Make call to AsyncTask 
     new AsyncFetch().execute(); 
    } 
    private class AsyncFetch extends AsyncTask<String, String, String> { 
     ProgressDialog pdLoading = new ProgressDialog(MainActivity.this); 
     HttpURLConnection conn; 
     URL url = null; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      //this method will be running on UI thread 
      pdLoading.setMessage("\tLoading..."); 
      pdLoading.setCancelable(false); 
      pdLoading.show(); 

     } 

     @Override 
     protected String doInBackground(String... params) { 
      try { 

       // Enter URL address where your json file resides 
       // Even you can make call to php file which returns json data 
       url = new URL("http://sayangoppa.com/ibn/jadwal.php"); 

      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       return e.toString(); 
      } 
      try { 

       // Setup HttpURLConnection class to send and receive data from php and mysql 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setReadTimeout(READ_TIMEOUT); 
       conn.setConnectTimeout(CONNECTION_TIMEOUT); 
       conn.setRequestMethod("GET"); 

       // setDoOutput to true as we recieve data from json file 
       conn.setDoOutput(true); 

      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
       return e1.toString(); 
      } 

      try { 

       int response_code = conn.getResponseCode(); 

       // Check if successful connection made 
       if (response_code == HttpURLConnection.HTTP_OK) { 

        // Read data sent from server 
        InputStream input = conn.getInputStream(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
        StringBuilder result = new StringBuilder(); 
        String line; 

        while ((line = reader.readLine()) != null) { 
         result.append(line); 
        } 

        // Pass data to onPostExecute method 
        return (result.toString()); 

       } else { 

        return ("unsuccessful"); 
       } 

      } catch (IOException e) { 
       e.printStackTrace(); 
       return e.toString(); 
      } finally { 
       conn.disconnect(); 
      } 


     } 

     @Override 
     protected void onPostExecute(String result) { 

      //this method will be running on UI thread 

      pdLoading.dismiss(); 
      List<DataFish> data = new ArrayList<>(); 

      pdLoading.dismiss(); 
      try { 

       JSONArray jArray = new JSONArray(result); 

       // Extract data from json and store into ArrayList as class objects 
       for (int i = 0; i < jArray.length(); i++) { 
        JSONObject json_data = jArray.getJSONObject(i); 
        DataFish fishData = new DataFish(); 
        fishData.matkul = json_data.getString("matkul"); 
        fishData.waktu_batal = json_data.getString("waktu_batal"); 
        fishData.waktu_pengganti = json_data.getString("waktu_pengganti"); 
        fishData.dosen = json_data.getString("dosen"); 
        fishData.ruang = json_data.getString("ruang"); 
        fishData.alasan = json_data.getString("alasan"); 
        data.add(fishData); 
       } 

       // Setup and Handover data to recyclerview 
       mRVFishPrice = (RecyclerView) findViewById(R.id.fishPriceList); 
       mAdapter = new AdapterFish(MainActivity.this, data); 
       mRVFishPrice.setAdapter(mAdapter); 
       mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this)); 

      } catch (JSONException e) { 
       Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show(); 
      } 
      mSwipeRefreshLayout.setRefreshing(false); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    /** 
    * 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"; 

     public PlaceholderFragment() { 
     } 

     /** 
     * 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; 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
      TextView textView = (TextView) rootView.findViewById(R.id.section_label); 
      textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER))); 
      return rootView; 
     } 
    } 

    /** 
    * A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
    * one of the sections/tabs/pages. 
    */ 
    public class SectionsPagerAdapter extends FragmentPagerAdapter { 

     public SectionsPagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
     switch (position){ 
      case 0: 
       Tab1 jadwal_hari_ini = new Tab1(); 
       return jadwal_hari_ini; 
      case 1: 
       Tab2 jadwal_batal = new Tab2(); 
       return jadwal_batal; 
      case 2: 
       Tab3 info_kampus = new Tab3(); 
       return info_kampus; 
     } 
     return null; 
     } 

     @Override 
     public int getCount() { 
      // Show 3 total pages. 
      return 3; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      switch (position) { 
       case 0: 
        return "Jadwal Hari Ini"; 
       case 1: 
        return "Jadwal Batal"; 
       case 2: 
        return "Info Kampus"; 
      } 
      return null; 
     } 
    } 
} 

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 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:id="@+id/main_content" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.example.lamberto.m_jadwal.MainActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:id="@+id/appbar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:paddingTop="@dimen/appbar_padding_top" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:layout_scrollFlags="scroll|enterAlways" 
      app:popupTheme="@style/AppTheme.PopupOverlay"> 

     </android.support.v7.widget.Toolbar> 

     <android.support.design.widget.TabLayout 
      android:id="@+id/tabs" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" /> 

    </android.support.design.widget.AppBarLayout> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior" /> 

</android.support.design.widget.CoordinatorLayout> 

activity_jadwal_batal.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <android.support.v4.widget.SwipeRefreshLayout 
     android:id="@+id/swifeRefresh" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <android.support.v7.widget.RecyclerView 
      android:id="@+id/fishPriceList" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:paddingTop="10dp" 
      android:layout_weight="1" 
      /> 

    </android.support.v4.widget.SwipeRefreshLayout> 

</LinearLayout> 

請告訴是什麼問題以及如何避免這種情況。在此先感謝

錯誤日誌:

04-03 19:43:57.785 2998-2998/com.example.lamberto.m_jadwal E/AndroidRuntime: FATAL EXCEPTION: main 
                      Process: com.example.lamberto.m_jadwal, PID: 2998 
                      java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference 
                       at com.example.lamberto.m_jadwal.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:193) 
                       at com.example.lamberto.m_jadwal.MainActivity$AsyncFetch.onPostExecute(MainActivity.java:83) 
                       at android.os.AsyncTask.finish(AsyncTask.java:667) 
                       at android.os.AsyncTask.-wrap1(AsyncTask.java) 
                       at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684) 
                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                       at android.os.Looper.loop(Looper.java:154) 
                       at android.app.ActivityThread.main(ActivityThread.java:6119) 
                       at java.lang.reflect.Method.invoke(Native Method) 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
+1

錯誤日誌添加到您的問題 – shmakova

+0

發表您的應用水平和gradle這個錯誤日誌兩者。 – DkThakur

+0

構建apk時沒有錯誤。但是當我運行該應用程序時出現錯誤,顯示「不幸的是,M-jadwal已經停止。」 –

回答

1

由於您沒有提供的logcat還可能有不止一個錯誤。 但是你設置你的內容查看兩次

刪除這些行

// Refresh Start 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_jadwal_batal); 
+0

已編輯。我已經輸入logcat –

0

誤差產生的原因是SwipeRefreshLayout返回null,因爲它是在一個單獨的XML文件(activity_jadwal_batal.xml)未在主XML。 所以第一膨脹這個XML與佈局編輯器的幫助,然後得到這個SwipeRefreshLayout,使用如下 -

View convertView = LayoutInflater.from(ctx).inflate(R.layout.activity_jadwal_batal, null); 
mSwipeRefreshLayout = (SwipeRefreshLayout)convertViewfindViewById(R.id.swifeRefresh); 

這裏CTX是你的活動範圍內。

+0

請用(SwipeRefreshLayout)convertView.findViewById(R.id.swifeRefresh)編輯你的代碼; – DkThakur

+0

該怎麼辦?對不起,我是在android開發 –

+0

@LambertoFredrickNababan新簡單地替換您的代碼super.onCreate(savedInstanceState); setContentView(R.layout.activity_jadwal_batal); //滑動刷新佈局 mSwipeRefreshLayout =(SwipeRefreshLayout)findViewById(R.id.swifeRefresh);給予。 – DkThakur

-1

替換代碼

super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_jadwal_batal); 
// Swipe Refresh Layout 
mSwipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swifeRefresh); 

// Setup and Handover data to recyclerview 
mRVFishPrice = (RecyclerView) findViewById(R.id.fishPriceList); 

//make this global 
View convertView = null; 

//with SwipeRefreshLayout 
convertView = LayoutInflater.from(this).inflate(R.layout.activity_jadwal_batal, null); 
mSwipeRefreshLayout = (SwipeRefreshLayout)convertView.findViewById(R.id.swifeRefresh); 


//with RecyclerView 
mRVFishPrice = (RecyclerView) convertView.findViewById(R.id.fishPriceList); 
+0

@LambertoFredrickNababan哦對不起編輯我的答案。 – DkThakur

+0

我得到了新的日誌錯誤 –

+0

你正在以錯誤的方式執行你的代碼。首先,做一些研究如何設計佈局以及如何使用它們。 – DkThakur

相關問題