在Android中创建json对象失败

时间:2015-09-01 05:12:26

标签: java android json

我的android应用程序中有一个登录页面和主菜单。在我的登录页面中,用户必须输入appcode,用户名和电子邮件。其中三个值具有单独的验证。 成功登录系统后,如果用户单击后退按钮,则用户无法返回登录页面。我在登录页面中添加了finish(); 。 如果用户点击后退按钮消息框提示并询问用户是否需要退出应用程序?

public void alertDialog() {
    new AlertDialog.Builder(MainMenuActivity.this)
            .setTitle("Message")
            .setMessage("Do you want to exit the from app?")
            .setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            finish();
                        }
                    })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            }).show();
}

如果没有用户停留且没有用户离开应用程序,并且重新启动用户需要重新输入其详细信息并继续。

除验证部分外,所有这些功能都在起作用。

如果我输入无效数据以继续应用,则会显示错误消息并关闭应用。

这是我的logcat。



09-01 10:39:56.541    8659-8659/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
09-01 10:39:57.001    8659-8674/com.NICT.nict D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
09-01 10:39:57.003    8659-8659/com.NICT.nict D/﹕ HostConnection::get() New Host Connection established 0xb42b3e60, tid 8659
09-01 10:39:57.013    8659-8659/com.NICT.nict D/Atlas﹕ Validating map...
09-01 10:39:57.048    8659-8674/com.NICT.nict D/﹕ HostConnection::get() New Host Connection established 0xb42b3fe0, tid 8674
09-01 10:39:57.063    8659-8674/com.NICT.nict I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-01 10:39:57.083    8659-8674/com.NICT.nict D/OpenGLRenderer﹕ Enabling debug mode 0
09-01 10:39:57.100    8659-8674/com.NICT.nict W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-01 10:39:57.100    8659-8674/com.NICT.nict W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43a9700, error=EGL_SUCCESS
09-01 10:40:03.606    8659-8659/com.NICT.nict W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
09-01 10:40:04.017    8659-8723/com.NICT.nict I/System.out﹕ http://demo.et.lk/nitcapi/api/login///
09-01 10:40:04.017    8659-8723/com.NICT.nict I/System.out﹕ Creation of json object failed




我该怎么办?

CNC中 验证码,

loginBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (!ServiceHandler.isOnline(getApplicationContext())) {
                MessageHandler.showMessage("No network connection",
                        getApplicationContext());
            }
            new Thread(new Runnable() {
                public void run() {

                    Looper.prepare();

                    String code = codeEdit.getText().toString();
                    String email = emailEdit.getText().toString();
                    String name = nameEdit.getText().toString();
                    if (code.length() == 0) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                MessageHandler.showMessage(
                                        "Please Enter the app code",
                                        getApplicationContext());
                                errorStatus = true;
                            }
                        });
                        ;
                    } else if (name.length() == 0) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                MessageHandler.showMessage(
                                        "Please Enter Your Name",
                                        getApplicationContext());
                                errorStatus = true;
                            }
                        });
                        ;
                    } else if (email.length() == 0) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                MessageHandler.showMessage(
                                        "Please Enter Your Email",
                                        getApplicationContext());
                                errorStatus = true;
                            }
                        });
                        ;
                    }

                    EmailValidator emailValidator = new EmailValidator();
                    if(!emailValidator.validate(email)){
                        runOnUiThread(new Runnable() {
                            public void run() {
                                MessageHandler.showMessage(
                                        "Invalid Email",
                                        getApplicationContext());
                                errorStatus = true;
                            }
                        });
                        ;
                    }

- Diyoda的编辑 -



package com.NICT.nict.services;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ServiceHandler {

	static String response = null;
	public final static int GET = 1;
	public final static int POST = 2;

	public ServiceHandler() {

	}

	/**
	 * Making service call
	 * 
	 * @url - url to make request
	 * @method - http request method
	 * */
	public String makeServiceCall(String url, int method) {
		return this.makeServiceCall(url, method, null);
	}

	/**
	 * Making service call
	 * 
	 * @url - url to make request
	 * @method - http request method
	 * @params - http request params
	 * */
	public String makeServiceCall(String url, int method,
			List<NameValuePair> params) {
		try {
			// http client
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpEntity httpEntity = null;
			HttpResponse httpResponse = null;

			// Checking http request method type
			if (method == POST) {
				HttpPost httpPost = new HttpPost(url);
				// adding post params
				if (params != null) {
					httpPost.setEntity(new UrlEncodedFormEntity(params));
				}

				httpResponse = httpClient.execute(httpPost);

			} else if (method == GET) {
				// appending params to url
				if (params != null) {
					String paramString = URLEncodedUtils
							.format(params, "utf-8");
					url += "?" + paramString;
				}
				HttpGet httpGet = new HttpGet(url);

				httpResponse = httpClient.execute(httpGet);

			}
			httpEntity = httpResponse.getEntity();
			response = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return response;

	}

	public static boolean isOnline(Context ctx) {
		ConnectivityManager cm;
		NetworkInfo info = null;
		try {
			cm = (ConnectivityManager) ctx
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			info = cm.getActiveNetworkInfo();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (info!=null&&!info.equals(null));
	}
}
&#13;
&#13;
&#13;

为Diyoda编辑3

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:fillViewport="true"
>

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

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:indeterminate="false" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/login_land_layout_margin"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@string/logo"
                android:src="@drawable/ic_logo" />

            <EditText
                android:id="@+id/codeEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:ems="10"
                android:hint="@string/code"
                android:textColorHint="#FFFFFF"
                android:inputType="textPassword" >

                <requestFocus />
            </EditText>

            <EditText
                android:id="@+id/nameEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:ems="10"
                android:hint="@string/name"
                android:textColorHint="#FFFFFF"
                android:inputType="textPersonName" />

            <EditText
                android:id="@+id/emailEdit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:ems="10"
                android:hint="@string/email"
                android:textColorHint="#FFFFFF"
                android:inputType="textEmailAddress" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/login_land_margin_both"
                android:layout_marginRight="@dimen/login_land_margin_both"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/loginBtn"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="30dp"
                    android:background="#0f4b9b"
                    android:text="@string/login"
                    android:textColor="@color/LoginButtonColor" />

            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <ImageView
            android:id="@+id/poweredBy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/poweredby"
            android:layout_alignParentBottom="true"
            android:scaleType="center"

            />
    </LinearLayout>


</RelativeLayout>

这是logcat。

&#13;
&#13;
09-01 14:16:17.792  27281-27281/com.NICT.nict D/dalvikvm﹕ GC_FOR_ALLOC freed 15742K (120399), 50% free 18992K/37328K, paused 59ms, total 64ms
09-01 14:16:17.803  27281-27291/com.NICT.nict I/System.out﹕ [CDS]close[60594]
09-01 14:16:17.804  27281-27291/com.NICT.nict I/System.out﹕ close [socket][/0.0.0.0:60594]
09-01 14:16:17.805  27281-27291/com.NICT.nict I/System.out﹕ close [socket][/0.0.0.0:60594]
09-01 14:16:25.170  27281-27281/com.NICT.nict I/View﹕ Touch down dispatch to android.widget.Button{438bb780 VFED..C. ........ 0,30-440,78 #7f090022 app:id/loginBtn}, event = MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=190.54907, y[0]=23.447815, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=106787772, downTime=106787772, deviceId=2, source=0x1002 }
09-01 14:16:25.492  27281-27281/com.NICT.nict I/View﹕ Touch up dispatch to android.widget.Button{438bb780 VFED..C. ...P.... 0,30-440,78 #7f090022 app:id/loginBtn}, event = MotionEvent { action=ACTION_UP, id[0]=0, x[0]=190.54907, y[0]=23.447815, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=106788116, downTime=106787772, deviceId=2, source=0x1002 }
09-01 14:16:25.493  27281-27281/com.NICT.nict V/Provider/Settings﹕ get setting for user 0 by user 0 so skipping cache
09-01 14:16:25.493  27281-27281/com.NICT.nict V/Provider/Settings﹕ from settings cache , name = sound_effects_enabled , value = 0
09-01 14:16:25.499  27281-27281/com.NICT.nict D/dalvikvm﹕ create interp thread : stack size=128KB
09-01 14:16:25.499  27281-27281/com.NICT.nict D/dalvikvm﹕ create new thread
09-01 14:16:25.500  27281-27281/com.NICT.nict D/dalvikvm﹕ new thread created
09-01 14:16:25.500  27281-27281/com.NICT.nict D/dalvikvm﹕ update thread list
09-01 14:16:25.500  27281-28060/com.NICT.nict D/dalvikvm﹕ threadid=17: interp stack at 0x55711000
09-01 14:16:25.500  27281-28060/com.NICT.nict D/dalvikvm﹕ init ref table
09-01 14:16:25.500  27281-28060/com.NICT.nict D/dalvikvm﹕ init mutex
09-01 14:16:25.500  27281-28060/com.NICT.nict D/dalvikvm﹕ threadid=17: created from interp
09-01 14:16:25.500  27281-27281/com.NICT.nict D/dalvikvm﹕ start new thread
09-01 14:16:25.501  27281-28060/com.NICT.nict D/dalvikvm﹕ threadid=17: notify debugger
09-01 14:16:25.501  27281-28060/com.NICT.nict D/dalvikvm﹕ threadid=17 (Thread-1149): calling run()
09-01 14:16:25.514  27281-28060/com.NICT.nict D/dalvikvm﹕ threadid=17: exiting
09-01 14:16:25.514  27281-28060/com.NICT.nict D/dalvikvm﹕ threadid=17: bye!
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

将对话框添加到主菜单。

  public void alertDialog() {
new AlertDialog.Builder(MainMenuActivity.this)
        .setTitle("Message")
        .setMessage("Do you want to exit the from app?")
        .setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    @TargetApi(11)
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        finish();
                    }
                })
        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @TargetApi(11)
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        }).show();

}