当前位置: 首页 > 知识库问答 >
问题:

程序正在运行,但当我单击post按钮时,它不会发送到服务器?

淳于升
2023-03-14

这是renungan.java

public class renungan extends AppCompatActivity{

AlertDialog alertDialog;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private NavigationView nvDrawer;

//untuk Posting
EditText judul_r, isi_r;
View view;

//untuk Renungan
String myJSON;

private static final String TAG_RESULT = "result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD = "address";
private static final String TAG_PHOTO = "gambar";

JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
//untuk Renungan

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

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    nvDrawer = (NavigationView) findViewById(R.id.NV_sidebar);

    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();

    //ini untuk muncul TOMBOL disebelah kiri
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    setupDrawerContent(nvDrawer);

    //utk Renungan
    list = (ListView) findViewById(R.id.Lv_renungan);
    personList = new ArrayList<HashMap<String, String>>();

    //utk Posting
    judul_r = (EditText)  findViewById(R.id.ET_judulrenungan);
    isi_r = (EditText) findViewById(R.id.ET_isirenungan);
}

@Override //ketika klik di ITEM yg ada di TOOLBAR
public boolean onOptionsItemSelected(MenuItem item) {

    if(mToggle.onOptionsItemSelected(item)){
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void setupDrawerContent (NavigationView navigationView){
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener(){
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem){
                    selectDrawerItem(menuItem);
                    return true;
                }
            }
    );
}

public void selectDrawerItem(MenuItem menuItem) {
    Fragment fragment = null;
    Class fragmentClass = null;
    switch (menuItem.getItemId()){
        case R.id.nav_renungan :
            fragmentClass = pertama.class;
            getData();
            break;

        case R.id.nav_post:
            fragmentClass = posting.class;
            break;

        case R.id.nav_account:
            fragmentClass = kedua.class;
            break;

        case R.id.nav_settings:
            fragmentClass = ketiga.class;
            break;

        case R.id.nav_logout:
            fragmentClass = keempat.class;
            break;
    }
    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.FL_content, fragment).commit();

    menuItem.setChecked(true);

    setTitle(menuItem.getTitle());

    mDrawerLayout.closeDrawers();
}

//utk renungan
public void getData(){
    class GetDataJSON extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://192.168.1.15/projectRenungan/getData.php");

            httppost.setHeader("Content Type", "application/json");

            InputStream inputStream = null;
            String result = null;
            try{
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null){
                    sb.append(line + "\n");
                }
                result = sb.toString();
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally {
                try{
                    if(inputStream != null) inputStream.close();
                }
                catch (Exception squish){

                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            myJSON = result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
} //utk renungan

//utk renungan
protected void showList(){
    try{
        JSONObject jsonObj = new JSONObject(myJSON);
        peoples = jsonObj.getJSONArray(TAG_RESULT);

        for(int i=0; i<peoples.length(); i++){
            JSONObject c = peoples.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String address = c.getString(TAG_ADD);
            String photo = c.getString(TAG_PHOTO);

            HashMap<String,String> persons = new HashMap<String, String>();

            persons.put(TAG_ID,id);
            persons.put(TAG_NAME,name);
            persons.put(TAG_ADD,address);
            persons.put(TAG_PHOTO,photo);

            personList.add(persons);
        }

        ListAdapter adapter = new SimpleAdapter(
                renungan.this, personList, R.layout.design_row,
                new String[]{TAG_ID,TAG_NAME,TAG_ADD, TAG_PHOTO},
                new int[]{R.id.tv_jmlviewer, R.id.tv_judul, R.id.tv_tanggal, R.id.IV_renungan}
        );

        list.setAdapter(adapter);
    }
    catch (JSONException e){
        e.printStackTrace();
    }
}//utk renungan


public void OnPost (View v){

    String judul = judul_r.getText().toString();
    String isi = isi_r.getText().toString();
    String type = "posting";

    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, judul, isi);
}
}

这是BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;

BackgroundWorker (Context ctx) {
    context = ctx;
}

@Override
protected String doInBackground(String... params) {
    String type = params[0];

    String login_url = "http://192.168.1.15/projectRenungan/login.php";        

    String register_url = "http://192.168.1.15/projectRenungan/register.php";    

    String posting_url = "http://192.168.1.15/projectRenungan/posting.php";        

    //UNTUK LOGIN
    if(type.equals("login")){
        try {
            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8")+"&"
                    +URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            //$result dari login.php masuk kesini
            return result;
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
    //UNTUK DATA REGISTER
    else if(type.equals("register")){
        try{
            String nama = params[1];
            String email = params[2];
            String no_hp = params[3];
            String password = params[4];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("nama","UTF-8")+"="+URLEncoder.encode(nama,"UTF-8")+"&"
                    +URLEncoder.encode("nohp","UTF-8")+"="+URLEncoder.encode(no_hp,"UTF-8")+"&"
                    +URLEncoder.encode("passwordword","UTF-8")+"="+URLEncoder.encode(password,"UTF-8")+"&"
                    +URLEncoder.encode("emailmail","UTF-8")+"="+URLEncoder.encode(email,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));

            String result="";
            String line="";
            while((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            //$result dari register.php masuk kesini
            return result;
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
    //UNTUK POSTING RENUNGAN
    else if(type.equals("posting")){
        try{

            String judul = params[1];
            String isi = params[2];

            URL url = new URL(posting_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("judul","UTF-8")+"="+URLEncoder.encode(judul,"UTF-8")+"&"
                    +URLEncoder.encode("isi","UTF-8")+"="+URLEncoder.encode(isi,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));

            String result="";
            String line="";
            while((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            //$result dari register.php masuk kesini
            return result;
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

    return null;
}

@Override
protected void onPreExecute() {
   alertDialog = new AlertDialog.Builder(context).create();
   alertDialog.setTitle("Login Status");
}

@Override //Setelah Login Sukses maupun Gagal
protected void onPostExecute(String result) {
    if(result.contains("login success")) {
        Intent i = new Intent(context, renungan.class);
        context.startActivity(i);
        alertDialog.setMessage(result);
        alertDialog.show();
    }
    else{
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}
public class posting extends Fragment {
EditText judul, isi;
View view;
Button btnPost;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.posting, container, false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ET_judulrenungan"
    android:hint="JUDUL" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/ET_judulrenungan"
    android:id="@+id/ET_isirenungan"
    android:hint="ISI" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POST"
        android:id="@+id/BTN_post"
        android:layout_weight="1"
        android:onClick="OnPost">

    </Button>
</RelativeLayout>

</LinearLayout>

当我点击“POST”按钮时,它是失败的

这是错误堆栈消息

共有1个答案

闻人景澄
2023-03-14

尝试更改以下内容:BackgroundWorker BackgroundWorker=new BackgroundWorker(renungan.THIS);

 类似资料:
  • 我试图在JavaFX中单击按钮时检索XLS文件并将其加载到TableView中。我使用Task类和ExecutorService来启动新线程。我需要reader类是可重用的,但是FileChooser没有出现。 这是我尝试编写一些并发代码。我想知道我做错了什么,我将如何改进我的代码,因为一切都是事件驱动的? 控制器类代码 阅读器类文件

  • 我想使用按钮单击中的GCM将推送通知从一个设备发送到多个设备。我遵循了GCM的所有流程。我获得了设备的服务器密钥和注册ID,但没有使用GCM获得推送通知。我也在谷歌上搜索过,但没有找到正确的解决方案。 请建议我如何在多设备上发送推送通知。 MAYActivity.java

  • 当我在设备上运行应用程序时单击增量按钮时,我的应用程序意外地强制执行这是我的activity_main.xml代码 这是我的mainactivity.java文件 这是调试报告05-23 22:14:45.695 297 36-29736/com.orton.birthdayCard E/AndroidRuntime:致命异常:主进程:com.orton.birthdayCard,PID:2973

  • 我需要在商品搜索中键入“香蕉”,然后点击“GO”按钮。 在堆栈溢出的帮助下,我可以调出火狐,输入“香蕉”...但是“Go”按钮(基于检查的Go3)不会开火!! 我试过element.click(),试过ActionChains,试过将光标移动到元素,试过验证它已经启用。它只是不会转到下一个搜索页面。 我没有得到任何错误...它只是没有进入下一页。 谢谢你能提供的任何帮助。快把我逼疯了!

  • 一切正常,应用程序出现了。但当我点击任何切换按钮时,应用程序就会崩溃。 我试过了,但找不到问题。其实我的知识还不够,我是这个领域的新手。所以请帮帮我。 这是查看活动。JAVA 还有这只logcat 2020-03-18 03:16:50.407 31609-31609/? E/lpaper。wallper:运行时设置的未知位_标志:0x8000 2020-03-18 03:17:04.862 31

  • 当我尝试单击应用程序中的按钮时,出现org . open QA . selenium . web driver exception。操作是单击按钮,执行停止并出现以下错误: 错误日志是: 线程“main”org.openqa.selenium中出现异常。WebDriverException:未知错误:元素…在点(337,11)处不可单击。其他元素将收到点击:…(会话信息:chrome=58.0.3