Java 不幸的是,应用程序m-jadwal已停止

Java 不幸的是,应用程序m-jadwal已停止,java,android,Java,Android,我正在构建一个应用程序,使用json解析和显示来自MySQL的数据。我正在为导航器使用选项卡式活动。当我构建apk时没有错误。但是当我运行我的应用程序时,我收到一个错误,不幸的是,m-jadwal已经停止。 项目文件: 这是我的代码文件: Gradle应用程序 apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultC

我正在构建一个应用程序,使用json解析和显示来自MySQL的数据。我正在为导航器使用选项卡式活动。当我构建apk时没有错误。但是当我运行我的应用程序时,我收到一个错误,不幸的是,m-jadwal已经停止。

项目文件:

这是我的代码文件:

Gradle应用程序

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

由于您尚未提供logcat,因此可能存在多个错误。 但是,您要设置contentView两次

拆下这些线

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

出现错误的原因是SwipeRefreshLayout返回null,因为它位于单独的xml文件(activity_jadwal_batal.xml)中,而不是主xml中。 因此,首先在布局编辑器的帮助下膨胀这个xml,然后得到这个布局,如下所示-

View convertView = LayoutInflater.from(ctx).inflate(R.layout.activity_jadwal_batal, null);
 mSwipeRefreshLayout = (SwipeRefreshLayout)convertViewfindViewById(R.id.swifeRefresh);
这里ctx是您的活动上下文。

替换您的代码

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


将错误日志添加到您的问题中发布您的应用程序级别梯度和错误日志。构建apk时没有错误。但当我运行应用程序时,出现一个错误,显示“很遗憾,M-jadwal已停止”。@LambertoFredrickNababan首先提供错误日志…和应用程序级别的渐变代码。@DkThakur没有错误日志。但是当我启动应用程序时,出现了错误。请使用(SwipeRefreshLayout)convertView.findViewById(R.id.swifeRefresh)编辑代码;我应该如何处理这些代码?对不起,我是android新手developing@LambertoFredrickNababan只需替换为您的代码super.onCreate(savedInstanceState);setContentView(R.layout.activity_jadwal_batal);//滑动刷新布局mSwipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.swifeRefresh);用这个代替上下文对不起,我不明白。但它不能解析符号“ctx”。我必须做什么?你以错误的方式编写代码。首先,研究一下如何设计布局以及如何使用它们。@LambertoFredrickNababan对recyclerview做同样的事情,比如View convertView=LayoutInflater.from(MainActivity.this)。充气(R.layout.activity\u jadwal\u batal,null);mRVFishPrice=(RecyclerView)convertView.findViewById(R.id.fishPriceList);更改此部分?//设置并将数据移交至recyclerview mRVFishPrice=(recyclerview)findViewById(R.id.fishPriceList);mAdapter=新适配器鱼(MainActivity.this,数据)@LambertoFredrickNababan仅替换为该//设置并将数据移交给recyclerview mRVFishPrice=(recyclerview)findViewById(R.id.fishPriceList);
// Refresh Start
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jadwal_batal);
View convertView = LayoutInflater.from(ctx).inflate(R.layout.activity_jadwal_batal, null);
 mSwipeRefreshLayout = (SwipeRefreshLayout)convertViewfindViewById(R.id.swifeRefresh);
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);